//
//  RCTVideo.m
//  RCTOMPlayer
//
//  Created by lcg on 2017/7/13.
//  Copyright © 2017年 Anren. All rights reserved.
//

#import "RCTVideo.h"
#import "UIView+React.h"
#import "RCTVideoToolbar.h"
#import "JX_GCDTimerManager.h"
#import "RCTVideoModule.h"
#import <MediaPlayer/MediaPlayer.h>

#define SYSTEM_VERSION_GREATER_THAN(v) ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] == NSOrderedDescending)
#define rateKey @"rate"
#define orientationKey @"orientation"

#define TOOLBAR_TIMER @"om_toolber_timer"
#define LOCK_BTN_TIMER @"om_lockBtn_timer"
#define PROGRESS_TIME @"om_progress_timer"
#define GESTURE_TIMER_TIMER @"om_gesture_timer"

@interface RCTVideo()<UIGestureRecognizerDelegate>

@property (nonatomic) MPVolumeView *volumeView;
@property (nonatomic, weak) RCTVideoToolbar *toolbar;
@property (nonatomic, weak) UISlider *gestureSlider;
@property (nonatomic, weak) UISlider *volumeViewSlider;
@property (nonatomic, weak) UIView *rootView;
@property (nonatomic, weak) UIView *speedBar;
@property (nonatomic, strong) UIButton *lockBtn;
@property (nonatomic, strong) UIButton *releaseBtn;
@property (nonatomic, strong) UIButton *releaseBtn2;
@property (nonatomic, weak) UIButton *rateBtn07;
@property (nonatomic, weak) UIButton *rateBtn10;
@property (nonatomic, weak) UIButton *rateBtn125;
@property (nonatomic, weak) UIButton *rateBtn15;
@property (nonatomic, weak) UIButton *rateBtn20;
@property (nonatomic, weak) UIView *fullscreenView;
@property (nonatomic, retain) NSTimer* timer;
@property (nonatomic, assign) NSString* orientation;
@property (nonatomic, assign) NSNumber* orientationValue;
@property (nonatomic, weak) UILabel *lblTotalTime;

@property (nonatomic, assign) float light;
@property (nonatomic, assign) float volumeValue;
@property (nonatomic, assign) BOOL isVolume;
@property (nonatomic, assign) float screenWidth;
@property (nonatomic, assign) float screenHeight;

@property (nonatomic, assign) BOOL controls;
@property (nonatomic, assign) BOOL lockScreen;
@property (nonatomic, assign) BOOL startTimer;
@property (nonatomic, assign) BOOL fullscreen;

@property (nonatomic, retain) NSLayoutConstraint *marginLeft;
@property (nonatomic, retain) NSLayoutConstraint *marginRight;
@property (nonatomic, retain) NSLayoutConstraint *marginBottom;
@property (nonatomic, retain) NSLayoutConstraint *toolbarHeight;

@property (nonatomic, assign) int textLeft;
@property (nonatomic, assign) int textTop;
@property (nonatomic, assign) int textWidth;
@property (nonatomic, assign) int textHeight;

@property (nonatomic, copy) RCTBubblingEventBlock onOMVideoLoadStart;
@property (nonatomic, copy) RCTBubblingEventBlock onOMVideoLoad;
@property (nonatomic, copy) RCTBubblingEventBlock onOMVideoLoadStalled;
@property (nonatomic, copy) RCTBubblingEventBlock onOMVideoLoadResume;
@property (nonatomic, copy) RCTBubblingEventBlock onOMVideoError;
@property (nonatomic, copy) RCTBubblingEventBlock onOMVideoProgress;
@property (nonatomic, copy) RCTBubblingEventBlock onOMVideoSeek;
@property (nonatomic, copy) RCTBubblingEventBlock onOMVideoEnd;
@property (nonatomic, copy) RCTBubblingEventBlock onOMVideoFullscreenPlayerWillPresent;
@property (nonatomic, copy) RCTBubblingEventBlock onOMVideoFullscreenPlayerDidPresent;
@property (nonatomic, copy) RCTBubblingEventBlock onOMVideoFullscreenPlayerWillDismiss;
@property (nonatomic, copy) RCTBubblingEventBlock onOMVideoFullscreenPlayerDidDismiss;
@property (nonatomic, copy) RCTBubblingEventBlock onOMReadyForDisplay;
@property (nonatomic, copy) RCTBubblingEventBlock onOMPlaybackStalled;
@property (nonatomic, copy) RCTBubblingEventBlock onOMPlaybackResume;
@property (nonatomic, copy) RCTBubblingEventBlock onOMPlaybackRateChange;
@property (nonatomic, copy) RCTBubblingEventBlock onOMVideoFullscreenOrientationChange;

@end

@implementation RCTVideo

- (instancetype)init
{
    if (self = [super init])
    {
        [self initRootView];
        [self initTouchEvents];
//        [[NSNotificationCenter defaultCenter] addObserver:self
//                                                 selector:@selector(deviceOrientationDidChange:)
//                                                     name:@"UIDeviceOrientationDidChangeNotification"
//                                                   object:nil];
    }

    return self;
}

- (void) setFullscreenDirectionAuto: (NSString *) orientation {
    if (orientation) {
        if ([orientation isEqual:(@"left")]) {
            self.orientation = @"left";
            [self turnLandscapeRight: NO];
        }
        if ([orientation isEqual:(@"right")]) {
            self.orientation = @"right";
            [self turnLandscapeRight: YES];
        }
    }

}

- (void)dealloc
{
//    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"UIDeviceOrientationDidChangeNotification" object:nil];
}

- (void)deviceOrientationDidChange:(NSNotification *)notification
{
//    [self updateConstraintsIfNeeded];
}

- (void)setMPVolume:(float)value {
     UISlider *volumeSlider = [self volumeSlider];
        self.volumeView.showsVolumeSlider = YES; // 需要设置 showsVolumeSlider 为 YES
        self.volumeView.alpha = 0.01f;
        [volumeSlider setValue:value animated:NO];
        [volumeSlider sendActionsForControlEvents:UIControlEventTouchUpInside];
        [self.volumeView sizeToFit];
        self.volumeViewSlider = volumeSlider;
}

- (MPVolumeView*)volumeView {
    if (!_volumeView) {
        _volumeView = [[MPVolumeView alloc] init];
//        _volumeView.hidden = YES;
        [self.rootView addSubview:_volumeView];
    }
    return _volumeView;
}
/*
 * 遍历控件，拿到UISlider
 */
- (UISlider *)volumeSlider {
    UISlider* volumeSlider = nil;
    for (UIView *view in [self.volumeView subviews]) {
        if ([view.class.description isEqualToString:@"MPVolumeSlider"]){
            volumeSlider = (UISlider *)view;
            break;
        }
    }
    return volumeSlider;
}

-(void) dispearLockBtn {
    [[JX_GCDTimerManager sharedInstance] cancelTimerWithName:LOCK_BTN_TIMER];
    [[JX_GCDTimerManager sharedInstance] scheduledDispatchTimerWithName:LOCK_BTN_TIMER
                                                           timeInterval:2
                                                                  queue:nil
                                                                repeats:NO
                                                           actionOption:AbandonPreviousAction
                                                                 action:^{
                                                                     dispatch_async(dispatch_get_main_queue(), ^{
                                                                         self.releaseBtn.hidden = YES;
                                                                         self.releaseBtn2.hidden = YES;
                                                                     });
                                                                 }];
}

-(void) dispearSlideGesture {
    [[JX_GCDTimerManager sharedInstance] cancelTimerWithName:GESTURE_TIMER_TIMER];
    [[JX_GCDTimerManager sharedInstance] scheduledDispatchTimerWithName:GESTURE_TIMER_TIMER
                                                           timeInterval:2
                                                                  queue:nil
                                                                repeats:NO
                                                           actionOption:AbandonPreviousAction
                                                                 action:^{
                                                                     dispatch_async(dispatch_get_main_queue(), ^{
                                                                         self.gestureSlider.hidden = YES;
                                                                     });
                                                                 }];
}

- (void) lockBtnClick:(id)sender {
    self.lockScreen = YES;
    self.lockBtn.hidden = YES;
    self.releaseBtn.hidden = NO;
    self.releaseBtn2.hidden = NO;
    self.toolbar.hidden = YES;
    self.gestureSlider.hidden = YES;
    [self dispearLockBtn];
}

- (void) releaseBtnClick:(id)sender {
    self.lockScreen = NO;
    self.releaseBtn.hidden = YES;
    self.releaseBtn2.hidden = YES;
    self.lockBtn.hidden = NO;
    self.toolbar.hidden = NO;
    [self getTransformRotationAngle];
}

- (void) turnLandscapeRight: (BOOL)goRight {
    CGAffineTransform rotation = goRight ? CGAffineTransformMakeRotation(M_PI_2) : CGAffineTransformMakeRotation(-M_PI_2);
    self.fullscreenView.transform = rotation;
    CGSize screenSize = [[UIScreen mainScreen] bounds].size;
    self.fullscreenView.frame = CGRectMake(0, 0, screenSize.width, screenSize.height);
    [[UIApplication sharedApplication] setStatusBarHidden:YES withAnimation:UIStatusBarAnimationNone];
    self.toolbar.center = CGPointMake(self.rootView.bounds.size.width / 2, self.rootView.bounds.size.height -30);
}

- (void)getTransformRotationAngle {
    if (!self.lockScreen) {
        UIDeviceOrientation orientation = [UIDevice currentDevice].orientation;
        // 根据要进行旋转的方向来计算旋转的角度
        if(orientation == UIInterfaceOrientationLandscapeRight){
            self.orientation = @"right";
            [self turnLandscapeRight: YES];
        }
        if (orientation == UIInterfaceOrientationLandscapeLeft){
            self.orientation = @"left";
            [self turnLandscapeRight: NO];
        }
    }
}

- (void) initSpeedBar {
    CGSize screenSize = [[UIScreen mainScreen] bounds].size;
    UIView *speedBar = [[UIView alloc] initWithFrame:CGRectMake(screenSize.height - 180, 0, 180, screenSize.width)];
    speedBar.backgroundColor = [UIColor colorWithRed:62.0 / 255.0f green:62.0 / 255.0f blue:62.0 / 255.0f alpha:0.70f];
    if (speedBar) {
        UIButton *rateBtn07 = [[UIButton alloc] init];
        [rateBtn07 setTitle:@"0.7 X" forState:UIControlStateNormal];
        rateBtn07.alpha = 0.7;
        rateBtn07.titleLabel.font = [UIFont systemFontOfSize: 16];
        [rateBtn07 addTarget:self action:@selector(setRate:) forControlEvents:UIControlEventTouchUpInside];
        self.rateBtn07 = rateBtn07;
        [speedBar addSubview: self.rateBtn07];

        UIButton *rateBtn10 = [[UIButton alloc] init];
        [rateBtn10 setTitle:@"1 X" forState:UIControlStateNormal];
        rateBtn10.alpha = 1.0;
        rateBtn10.titleLabel.font = [UIFont systemFontOfSize: 16];
        [rateBtn10 addTarget:self action:@selector(setRate:) forControlEvents:UIControlEventTouchUpInside];
        self.rateBtn10 = rateBtn10;
        [speedBar addSubview: self.rateBtn10];

        UIButton *rateBtn125 = [[UIButton alloc] init];
        [rateBtn125 setTitle:@"1.25 X" forState:UIControlStateNormal];
        rateBtn125.alpha = 1.25;
        rateBtn125.titleLabel.font = [UIFont systemFontOfSize: 16];
        [rateBtn125 addTarget:self action:@selector(setRate:) forControlEvents:UIControlEventTouchUpInside];
        self.rateBtn125 = rateBtn125;
        [speedBar addSubview: self.rateBtn125];

        UIButton *rateBtn15 = [[UIButton alloc] init];
        [rateBtn15 setTitle:@"1.5 X" forState:UIControlStateNormal];
        rateBtn15.alpha = 1.5;
        rateBtn15.titleLabel.font = [UIFont systemFontOfSize: 16];
        [rateBtn15 addTarget:self action:@selector(setRate:) forControlEvents:UIControlEventTouchUpInside];
        self.rateBtn15 = rateBtn15;
        [speedBar addSubview: self.rateBtn15];

        UIButton *rateBtn20 = [[UIButton alloc] init];
        [rateBtn20 setTitle:@"2 X" forState:UIControlStateNormal];
        rateBtn20.alpha = 2.0;
        rateBtn20.titleLabel.font = [UIFont systemFontOfSize: 16];
        [rateBtn20 addTarget:self action:@selector(setRate:) forControlEvents:UIControlEventTouchUpInside];
        [speedBar addSubview: rateBtn20];
        self.rateBtn20 = rateBtn20;
        [speedBar addSubview: self.rateBtn20];

        rateBtn07.translatesAutoresizingMaskIntoConstraints = NO;
        rateBtn10.translatesAutoresizingMaskIntoConstraints = NO;
        rateBtn125.translatesAutoresizingMaskIntoConstraints = NO;
        rateBtn15.translatesAutoresizingMaskIntoConstraints = NO;
        rateBtn20.translatesAutoresizingMaskIntoConstraints = NO;

        self.speedBar = speedBar;
//        self.speedBar.hidden = YES;
        [self.rootView addSubview:self.speedBar];
        [self.rootView bringSubviewToFront:self.speedBar];
        [self setRateBtnConstraints];
    }
}

- (void)initRootView
{
    UIView *rootView = [[UIView alloc] init];
    rootView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
    [self addSubview:rootView];
    self.startTimer = NO;
    self.textLeft = 10;
    self.textTop = 10;
    self.lockScreen = NO;
    self.player = [[RCTMediaPlayer alloc] init];
    self.player.delegate = self;
    self.player.parent = rootView;

    RCTVideoToolbar *toolbar = [[RCTVideoToolbar alloc] initWithFrame:CGRectMake(0, 0, 0, 0)];
    toolbar.translatesAutoresizingMaskIntoConstraints = NO;
    toolbar.delegate = self;
    toolbar.hidden = YES;
    toolbar.backgroundColor = [UIColor colorWithRed:62.0 / 255.0f green:62.0 / 255.0f blue:62.0 / 255.0f alpha:0.80f];
    toolbar.layer.cornerRadius = 12;
    toolbar.layer.masksToBounds = YES;
    [rootView addSubview:toolbar];

    self.rootView = rootView;
    self.toolbar = toolbar;

    [self updateConstraintsIfNeeded];
}

- (void)setRateBtnConstraints
{
    [self setRate07Constrains];
    [self setRate10Constrains];
    [self setRate125Constrains];
    [self setRate15Constrains];
    [self setRate20Constrains];
}

- (void)setRate07Constrains
{

    NSLayoutConstraint *hCenter = [NSLayoutConstraint constraintWithItem:self.rateBtn07
                                                               attribute:NSLayoutAttributeCenterY
                                                               relatedBy:NSLayoutRelationEqual
                                                                  toItem:self.speedBar
                                                               attribute:NSLayoutAttributeCenterY
                                                              multiplier:1
                                                                constant:-100];

    NSLayoutConstraint *wCenter = [NSLayoutConstraint constraintWithItem:self.rateBtn07
                                                               attribute:NSLayoutAttributeCenterX
                                                               relatedBy:NSLayoutRelationEqual
                                                                  toItem:self.speedBar
                                                               attribute:NSLayoutAttributeCenterX
                                                              multiplier:1
                                                                constant:0.5];

    [self.speedBar addConstraints:[NSArray arrayWithObjects:hCenter, wCenter, nil]];
}

- (void)setRate10Constrains
{

    NSLayoutConstraint *hCenter = [NSLayoutConstraint constraintWithItem:self.rateBtn10
                                                               attribute:NSLayoutAttributeCenterY
                                                               relatedBy:NSLayoutRelationEqual
                                                                  toItem:self.speedBar
                                                               attribute:NSLayoutAttributeCenterY
                                                              multiplier:1
                                                                constant:-50];

    NSLayoutConstraint *wCenter = [NSLayoutConstraint constraintWithItem:self.rateBtn10
                                                               attribute:NSLayoutAttributeCenterX
                                                               relatedBy:NSLayoutRelationEqual
                                                                  toItem:self.speedBar
                                                               attribute:NSLayoutAttributeCenterX
                                                              multiplier:1
                                                                constant:0.5];

    [self.speedBar addConstraints:[NSArray arrayWithObjects:hCenter, wCenter, nil]];
}

- (void)setRate125Constrains
{

    NSLayoutConstraint *hCenter = [NSLayoutConstraint constraintWithItem:self.rateBtn125
                                                               attribute:NSLayoutAttributeCenterY
                                                               relatedBy:NSLayoutRelationEqual
                                                                  toItem:self.speedBar
                                                               attribute:NSLayoutAttributeCenterY
                                                              multiplier:1
                                                                constant:0];

    NSLayoutConstraint *wCenter = [NSLayoutConstraint constraintWithItem:self.rateBtn125
                                                               attribute:NSLayoutAttributeCenterX
                                                               relatedBy:NSLayoutRelationEqual
                                                                  toItem:self.speedBar
                                                               attribute:NSLayoutAttributeCenterX
                                                              multiplier:1
                                                                constant:0.5];

    [self.speedBar addConstraints:[NSArray arrayWithObjects:hCenter, wCenter, nil]];
}

- (void)setRate15Constrains
{

    NSLayoutConstraint *hCenter = [NSLayoutConstraint constraintWithItem:self.rateBtn15
                                                               attribute:NSLayoutAttributeCenterY
                                                               relatedBy:NSLayoutRelationEqual
                                                                  toItem:self.speedBar
                                                               attribute:NSLayoutAttributeCenterY
                                                              multiplier:1
                                                                constant:50];

    NSLayoutConstraint *wCenter = [NSLayoutConstraint constraintWithItem:self.rateBtn15
                                                               attribute:NSLayoutAttributeCenterX
                                                               relatedBy:NSLayoutRelationEqual
                                                                  toItem:self.speedBar
                                                               attribute:NSLayoutAttributeCenterX
                                                              multiplier:1
                                                                constant:0.5];

    [self.speedBar addConstraints:[NSArray arrayWithObjects:hCenter, wCenter, nil]];
}

- (void)setRate20Constrains
{

    NSLayoutConstraint *hCenter = [NSLayoutConstraint constraintWithItem:self.rateBtn20
                                                               attribute:NSLayoutAttributeCenterY
                                                               relatedBy:NSLayoutRelationEqual
                                                                  toItem:self.speedBar
                                                               attribute:NSLayoutAttributeCenterY
                                                              multiplier:1
                                                                constant:100];

    NSLayoutConstraint *wCenter = [NSLayoutConstraint constraintWithItem:self.rateBtn20
                                                               attribute:NSLayoutAttributeCenterX
                                                               relatedBy:NSLayoutRelationEqual
                                                                  toItem:self.speedBar
                                                               attribute:NSLayoutAttributeCenterX
                                                              multiplier:1
                                                                constant:0.5];

    [self.speedBar addConstraints:[NSArray arrayWithObjects:hCenter, wCenter, nil]];
}

- (void)updateConstraints
{
    CGFloat constantMarginLeft = 20.0f;
    CGFloat constantMarginRight = -20.0f;
    CGFloat constantBottom = -10.0f;

    CGSize screenSize = [[UIScreen mainScreen] bounds].size;

    if (screenSize.width == 812 && screenSize.height == 375)
    {
        constantMarginLeft = 44.0f;
        constantMarginRight = -44.0f;
        constantBottom = -24.0f;
    }

    [self.rootView removeConstraints: [NSArray arrayWithObjects: self.marginLeft, self.marginRight, self.marginBottom, self.toolbarHeight, nil]];

    self.marginLeft = [NSLayoutConstraint constraintWithItem:self.toolbar
                                                   attribute:NSLayoutAttributeLeft
                                                   relatedBy:NSLayoutRelationEqual
                                                      toItem:self.rootView
                                                   attribute:NSLayoutAttributeLeft
                                                  multiplier:1
                                                    constant:constantMarginLeft];

    self.marginRight = [NSLayoutConstraint constraintWithItem:self.toolbar
                                                    attribute:NSLayoutAttributeRight
                                                    relatedBy:NSLayoutRelationEqual
                                                       toItem:self.rootView
                                                    attribute:NSLayoutAttributeRight
                                                   multiplier:1
                                                     constant:constantMarginRight];

    self.marginBottom = [NSLayoutConstraint constraintWithItem:self.toolbar
                                                     attribute:NSLayoutAttributeBottom
                                                     relatedBy:NSLayoutRelationEqual
                                                        toItem:self.rootView
                                                     attribute:NSLayoutAttributeBottom
                                                    multiplier:1
                                                      constant:constantBottom];

    self.toolbarHeight = [NSLayoutConstraint constraintWithItem:self.toolbar
                                                      attribute:NSLayoutAttributeHeight
                                                      relatedBy:NSLayoutRelationEqual
                                                         toItem:nil
                                                      attribute:NSLayoutAttributeNotAnAttribute
                                                     multiplier:1
                                                       constant:40];

    [self.rootView addConstraints:[NSArray arrayWithObjects: self.marginLeft, self.marginRight, self.marginBottom, self.toolbarHeight, nil]];


    [self initTimer];

    [super updateConstraints];
}

- (void)initTouchEvents
{
    UITapGestureRecognizer *tapRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapRecognizer:)];
    UIPanGestureRecognizer *panRecognizer = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(panRecognizer:)];

    tapRecognizer.delegate = self;
    panRecognizer.delegate = self;

    [self addGestureRecognizer:tapRecognizer];
    [self addGestureRecognizer:panRecognizer];
}

- (void)tapRecognizer:(UITapGestureRecognizer*)tapRecognizer
{
    if (self.fullscreen && self.speedBar && self.speedBar.hidden == NO) {
        CGPoint locationPoint = [tapRecognizer locationInView:self];
        BOOL contains = CGRectContainsPoint(self.speedBar.frame, locationPoint);
        if (!contains) {
            self.speedBar.hidden = YES;
        }
    }
}

- (void) changeVolume:(CGFloat) value  {
    if (!self.gestureSlider) {
        [self initGestureSlider];
    }
    self.gestureSlider.hidden = NO;
    [self.gestureSlider setMinimumValueImage:[UIImage imageNamed:@"volume.png"]];
    self.gestureSlider.value = self.volumeViewSlider.value;
    self.volumeViewSlider.value -= value / 10000;
    [self setMPVolume: self.volumeViewSlider.value];
    [self.gestureSlider setValue: self.volumeViewSlider.value];
}

- (void) changeLight:(CGFloat) value {
    if (!self.gestureSlider) {
        [self initGestureSlider];
    }
    self.gestureSlider.hidden = NO;
    [self.gestureSlider setMinimumValueImage:[UIImage imageNamed:@"screen_light.png"]];
    self.gestureSlider.value = [UIScreen mainScreen].brightness;
    [UIScreen mainScreen].brightness -= value / 10000;
    [self.gestureSlider setValue: [UIScreen mainScreen].brightness];
}

- (void)panRecognizer:(UIPanGestureRecognizer *) pan
{
    if(self.fullscreen == NO || self.lockScreen){
        return;
    }

    if (self.speedBar && self.speedBar.hidden == NO) {
        self.toolbar.hidden = YES;
        [self hideAllLockBtn];
        return;
    }

    CGSize screenSize = [[UIScreen mainScreen] bounds].size;
    //根据在view上Pan的位置，确定是调音量还是亮度
    CGFloat locationPoint = [pan locationInView:self.fullscreenView].x;
    // 我们要响应水平移动和垂直移动
    // 根据上次和本次移动的位置，算出一个速率的point
    CGPoint veloctyPoint = [pan velocityInView:self];
    switch (pan.state) {
        case UIGestureRecognizerStateBegan:{ // 开始移动
            self.toolbar.hidden = YES;
            [self hideAllLockBtn];
            break;
        }
        case UIGestureRecognizerStateChanged:{ // 正在移动
            CGFloat x = fabs(veloctyPoint.x);
            CGFloat y = fabs(veloctyPoint.y);
            if (x > y){ // 垂直移动

                // 开始滑动的时候,状态改为正在控制音量
                if ([self.orientation isEqual:(@"left")] || [self.player.orientation isEqual:(@"left")]) {

                    if (locationPoint < 180) {
                        [self changeLight: veloctyPoint.x];
                    }
                    if (locationPoint > screenSize.height - 180)
                    {
                        [self changeVolume: veloctyPoint.x];
                    }
                }

                if ([self.orientation isEqual:(@"right")]  || [self.player.orientation isEqual:(@"right")]) {
                    if (locationPoint < 180) {
                         [self changeLight: -veloctyPoint.x];
                    }
                    if (locationPoint > screenSize.height - 180)
                    {
                        [self changeVolume: -veloctyPoint.x];
                    }
                }

            }
            self.toolbar.hidden = YES;
            [self hideAllLockBtn];
            break;
        }
        case UIGestureRecognizerStateEnded:{
            [self dispearSlideGesture];
            break;
        }
        case UIGestureRecognizerStateCancelled: {
            break;
        }
        default:
            break;
    }
}

- (void)verticalMoved:(CGFloat)value {
    if (!self.gestureSlider) {
        [self initGestureSlider];
    }
}

- (BOOL)gestureRecognizerShouldBegin:(UIGestureRecognizer *)gestureRecognizer
{
    CGPoint point = [gestureRecognizer locationInView:self.toolbar];
    CGSize toolbarSize = self.toolbar.bounds.size;
    BOOL pointInToolbar = point.x >= 0 && point.x <= toolbarSize.width && point.y >= 0 && point.y <= toolbarSize.height;

    [self showToolbar:pointInToolbar];

    return !pointInToolbar;
}

- (void) showLockBtn {
    if (self.lockScreen) {
        self.releaseBtn.hidden = NO;
        self.releaseBtn2.hidden = NO;
    } else {
        self.lockBtn.hidden = NO;
    }
}

- (void) hideAllLockBtn {
    self.releaseBtn.hidden = YES;
    self.releaseBtn2.hidden = YES;
    self.lockBtn.hidden = YES;
}

-(void) dispearToolbar {
    [[JX_GCDTimerManager sharedInstance] cancelTimerWithName:TOOLBAR_TIMER];
    [[JX_GCDTimerManager sharedInstance] scheduledDispatchTimerWithName:TOOLBAR_TIMER
                                                           timeInterval:6
                                                                  queue:nil
                                                                repeats:NO
                                                           actionOption:AbandonPreviousAction
                                                                 action:^{
                                                                     dispatch_async(dispatch_get_main_queue(), ^{
                                                                         self.lockBtn.hidden = YES;
                                                                         self.toolbar.hidden = YES;
                                                                     });
                                                                 }];
}

- (void)showToolbar:(BOOL)forceShow
{

    if (!self.controls)
    {
        return;
    }

    if (self.fullscreen) {
        self.toolbar.center = CGPointMake(self.rootView.bounds.size.width / 2, self.rootView.bounds.size.height -30);
    }

    if (self.fullscreen && self.speedBar && self.speedBar.hidden == NO) {
        self.toolbar.hidden = YES;
        self.gestureSlider.hidden = YES;
        [self hideAllLockBtn];
        return;
    }

    if (self.toolbar.hidden || forceShow)
    {
        self.toolbar.hidden = NO;
        [self showLockBtn];
        [self.rootView bringSubviewToFront:self.toolbar];
        if (self.lockScreen) {
            self.toolbar.hidden = YES;
        }
        [self dispearToolbar];
        [self dispearLockBtn];
    }
    else
    {
        self.toolbar.hidden = YES;
        self.gestureSlider.hidden = YES;
        [self hideAllLockBtn];
    }
}

- (void) initTimer
{
    if (self.player.paused == NO && self.startTimer == NO) {
        self.startTimer = YES;
        [self getRandomPos];
        UILabel *lblTotalTime = [[UILabel alloc] initWithFrame:CGRectMake(self.textLeft, self.textTop, self.textWidth , self.textHeight)];
        [lblTotalTime setTextColor:[UIColor whiteColor]];
        lblTotalTime.alpha = 0.35;
        [lblTotalTime setFont:[UIFont fontWithName:@"Helvetica-Bold" size:self.player.displayTextSize ]];
        [lblTotalTime setText:self.player.displayText];
        [self.rootView addSubview:lblTotalTime];
        self.lblTotalTime = lblTotalTime;
        NSString *timerName = [NSString stringWithFormat:@"timer_%p", self];

        [[JX_GCDTimerManager sharedInstance] scheduledDispatchTimerWithName:timerName
                                                               timeInterval:self.player.displayDelay
                                                                      queue:nil
                                                                    repeats:YES
                                                               actionOption:AbandonPreviousAction
                                                                     action:^{
                                                                         dispatch_async(dispatch_get_main_queue(), ^{
                                                                             if(self.player.paused == NO) {
                                                                                 [self getRandomPos];
                                                                                 CGRect lableFrame = self.lblTotalTime.frame;

                                                                                 lableFrame.origin.x = self.textLeft;
                                                                                 lableFrame.origin.y = self.textTop;
                                                                                 self.lblTotalTime.frame = lableFrame;
                                                                             }
//                                                                             [self.lblTotalTime removeFromSuperview];
//                                                                             UILabel *lblTotalTime = [[UILabel alloc] initWithFrame:CGRectMake(self.textLeft, self.textTop, self.textWidth, self.textHeight)];
//                                                                             self.lblTotalTime = lblTotalTime;
//                                                                             [lblTotalTime setTextColor:[UIColor redColor]];
//                                                                             [lblTotalTime setFont:[UIFont systemFontOfSize:self.player.displayTextSize]];
//                                                                             [lblTotalTime setText:self.player.displayText];
//                                                                             [self.rootView addSubview:lblTotalTime];
                                                                             //                                                                         [self removePlayerTimer];
                                                                         });
                                                                     }];
    }
}
-(void) getRandomPos
{
    float limitX = 0.25f;
    float limitY = 0.25f;
    if (self.lblTotalTime == nil) {
        UILabel *lblTotalTime = [[UILabel alloc] init];
        [lblTotalTime setTextColor:[UIColor whiteColor]];
        lblTotalTime.alpha = 0.35;
        [lblTotalTime setFont:[UIFont fontWithName:@"Helvetica-Bold" size:self.player.displayTextSize ]];
        [lblTotalTime setText:self.player.displayText];

        CGSize size = [lblTotalTime.text sizeWithAttributes:@{NSFontAttributeName: [UIFont systemFontOfSize:self.player.displayTextSize]}];
        //ceilf()向上取整函数, 只要大于1就取整数2. floor()向下取整函数, 只要小于2就取整数1.
        CGSize adaptionSize = CGSizeMake(ceilf(size.width), ceilf(size.height));
        lblTotalTime.frame = CGRectMake(100, 100, adaptionSize.width, adaptionSize.height);
                self.textWidth = adaptionSize.width;
                self.textHeight = adaptionSize.height;
        self.lblTotalTime = lblTotalTime;
    }

    int windowWidth = self.rootView.frame.size.width;
    int windowHeight = self.rootView.frame.size.height;


    int randomX = arc4random() % (windowWidth - self.textWidth - 0 + 1)+ 0;
    int randomY = arc4random() % (windowHeight - self.textHeight - 0 + 1) + 0;
    bool isOutX = randomX > (windowWidth * limitX - self.textWidth) && randomX < windowWidth * (1 - limitX);
    bool isOutY = randomY > (windowHeight * limitY - self.textHeight) && randomY < windowHeight * (1 - limitY);

    if (isOutX && isOutY) {
        if ((randomX + self.textWidth / 2) > windowWidth / 2) {
            randomX = windowWidth * (1 - limitX);
        } else {
            randomX = windowWidth * limitX - self.textWidth;
        }
    }
    self.textLeft = randomX;
    self.textTop = randomY;
}

- (void)removePlayerTimer
{
    if (self.player.paused == YES && self.startTimer == YES) {
        self.startTimer = NO;
        NSString *timerName = [NSString stringWithFormat:@"timer_%p", self];
        [[JX_GCDTimerManager sharedInstance] cancelTimerWithName:timerName];
        [self.lblTotalTime removeFromSuperview];
        self.lblTotalTime = nil;
    }
}

- (void)removeFromSuperview
{
    [[JX_GCDTimerManager sharedInstance] cancelTimerWithName:TOOLBAR_TIMER];

    [self.player stop];
    self.player.delegate = nil;
    self.player.parent = nil;
    self.player = nil;

    [self.toolbar removeFromSuperview];
    self.toolbar.delegate = nil;
    self.toolbar = nil;

    [self.rootView removeFromSuperview];
    self.rootView = nil;

    [self releaseFullscreen];
}

- (void)createFullscreen
{
    [self releaseFullscreen];

    UIWindow *keyWindow = [[UIApplication sharedApplication] keyWindow];

    UIView *fullscreenView = [[UIView alloc] initWithFrame:keyWindow.bounds];
    [fullscreenView setBackgroundColor:[UIColor blackColor]];
    fullscreenView.autoresizingMask = UIViewAutoresizingFlexibleWidth|UIViewAutoresizingFlexibleHeight;

    UITapGestureRecognizer *tapRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapRecognizer:)];
    tapRecognizer.delegate = self;
    [fullscreenView addGestureRecognizer:tapRecognizer];

    UIPanGestureRecognizer *panRecognizer = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(panRecognizer:)];
    panRecognizer.delegate = self;
    [fullscreenView addGestureRecognizer:panRecognizer];

    [keyWindow addSubview:fullscreenView];

    self.fullscreenView = fullscreenView;
    [RCTVideoModule setFullScreenView:fullscreenView];
}

- (void)releaseFullscreen
{
    if (self.fullscreenView)
    {
        [self.fullscreenView removeFromSuperview];
        self.fullscreenView = nil;
    }
}

#pragma mark - props

- (void)setFullscreen:(BOOL)fullscreen
{
    _fullscreen = fullscreen;

    if (!self.fullscreenView)
    {
        [self createFullscreen];
    }

    if (self.fullscreen)
    {
        if (self.onOMVideoFullscreenPlayerWillPresent)
        {
            self.onOMVideoFullscreenPlayerWillPresent(@{});
        }

        [self.rootView removeFromSuperview];
        [self.rootView setFrame:self.fullscreenView.bounds];
        [self.fullscreenView addSubview:self.rootView];

        if (self.onOMVideoFullscreenPlayerDidPresent)
        {
            self.onOMVideoFullscreenPlayerDidPresent(@{});
        }
    }
    else
    {
        if (self.onOMVideoFullscreenPlayerWillDismiss)
        {
            self.onOMVideoFullscreenPlayerWillDismiss(@{});
        }

        [self.rootView removeFromSuperview];
        [self releaseFullscreen];
        [self.rootView setFrame:self.bounds];
        [self addSubview:self.rootView];

        if (self.onOMVideoFullscreenPlayerDidDismiss)
        {
            self.onOMVideoFullscreenPlayerDidDismiss(@{});
        }
    }

    [self.toolbar setFullscreen:fullscreen];

}

- (void)setControls:(BOOL)controls
{
    _controls = controls;

    if (controls)
    {
        [self showToolbar: NO];
    }
    else
    {
        [self.toolbar setHidden:YES];
    }
}

#pragma mark - RCToolbarDelegate

- (void)play
{

    self.player.paused = NO;
    self.toolbar.paused = NO;
    [self showToolbar: YES];
    [self initTimer];
}

- (void)rated: (BOOL)rated
{

    if (rated) {
        if (![self.speedBar isDescendantOfView:self.rootView]) {
            [self initSpeedBar];
        }
        [self setRatePanelState];
        [self showToolbar: NO];
        self.speedBar.hidden = NO;
    }
}

- (void) setRate: (id)sender
{
    UIButton *buttonClicked = (UIButton *)sender;
    [self rate: buttonClicked.alpha];
    if (self.player.rate) [self setRateState];
}

- (void) setRateState {
    [self setRatePanelState];
    [self setRateBtnState];
    [self sendCallbackEventToRN];
}

- (void) setRateBtnState {
    UIButton *rateBtn = (UIButton *)[self.toolbar viewWithTag:123];
    [rateBtn setTitle:[self getRateTitle: self.player.rate] forState:UIControlStateNormal];
}

- (void) setRatePanelState {
    CGFloat rate = self.player.rate;

    UIColor *touchGreen = [UIColor colorWithRed:21.0 / 255.0f green:196.0 / 255.0f blue:189.0 / 255.0f alpha:1.0f];
    [_rateBtn07 setTitleColor: rate == _rateBtn07.alpha ? touchGreen :  [UIColor whiteColor] forState:UIControlStateNormal];
    _rateBtn07.titleLabel.font = rate == _rateBtn07.alpha ? [UIFont fontWithName:@"Helvetica-Bold" size:18] : [UIFont systemFontOfSize: 16];
    [_rateBtn10 setTitleColor: rate == _rateBtn10.alpha ? touchGreen :  [UIColor whiteColor] forState:UIControlStateNormal];
    _rateBtn10.titleLabel.font = rate == _rateBtn10.alpha ? [UIFont fontWithName:@"Helvetica-Bold" size:18] : [UIFont systemFontOfSize: 16];
    [_rateBtn125 setTitleColor: rate == _rateBtn125.alpha ? touchGreen :  [UIColor whiteColor] forState:UIControlStateNormal];
    _rateBtn125.titleLabel.font = rate == _rateBtn125.alpha ? [UIFont fontWithName:@"Helvetica-Bold" size:18] : [UIFont systemFontOfSize: 16];
    [_rateBtn15 setTitleColor: rate == _rateBtn15.alpha ? touchGreen :  [UIColor whiteColor] forState:UIControlStateNormal];
    _rateBtn15.titleLabel.font = rate == _rateBtn15.alpha ? [UIFont fontWithName:@"Helvetica-Bold" size:18] : [UIFont systemFontOfSize: 16];
    [_rateBtn20 setTitleColor: rate == _rateBtn20.alpha ? touchGreen :  [UIColor whiteColor] forState:UIControlStateNormal];
    _rateBtn20.titleLabel.font = rate == _rateBtn20.alpha ? [UIFont fontWithName:@"Helvetica-Bold" size:18] : [UIFont systemFontOfSize: 16];
}

- (NSString*) getRateTitle: (float) rate {
    NSString *rateTitle = @"倍速";
    if (rate == 1.0) {

        return rateTitle;
    }
    return rateTitle = [NSString stringWithFormat: rate == 1.25 ? @"%.2f X" : @"%.1f X", rate];
}

- (void) sendCallbackEventToRN {
    NSDictionary *rateDict = @{ rateKey: @(self.player.rate) };
    [self OnPlaybackRateChange: rateDict];
}

- (void) sendScreenOrientationToRN {
    NSDictionary *orientationDict = @{ orientationKey: self.orientation };
    [self OnOrientationChange: orientationDict];
}

- (void)rate: (float)rate
{

    self.player.rate = rate;
    [self setRateBtnState];
}

- (void)pause
{

    self.player.paused = YES;
    self.toolbar.paused = YES;

    [self showToolbar: YES];
//    [self removePlayerTimer];
}

-(void) initLockBtns {
    CGSize screenSize = [[UIScreen mainScreen] bounds].size;
    _lockBtn = [[UIButton alloc] initWithFrame:CGRectMake(screenSize.height - 100, screenSize.width / 2 - 25, 50, 50)];
    [_lockBtn setImage:[UIImage imageNamed:@"release_screen.png"] forState:UIControlStateNormal];
    [_lockBtn addTarget:self action:@selector(lockBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    [self.rootView addSubview:_lockBtn];

    _releaseBtn = [[UIButton alloc] initWithFrame:CGRectMake(screenSize.height - 100, screenSize.width / 2 - 25, 50, 50)];
    [_releaseBtn setImage:[UIImage imageNamed:@"lock_screen.png"] forState:UIControlStateNormal];
    [_releaseBtn addTarget:self action:@selector(releaseBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    [self.rootView addSubview:_releaseBtn];

    _releaseBtn2 = [[UIButton alloc] initWithFrame:CGRectMake(50, screenSize.width / 2 - 25, 50, 50)];
    [_releaseBtn2 setImage:[UIImage imageNamed:@"lock_screen.png"] forState:UIControlStateNormal];
    [_releaseBtn2 addTarget:self action:@selector(releaseBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    [self.rootView addSubview:_releaseBtn2];
    [self hideAllLockBtn];

    [[NSNotificationCenter defaultCenter]
     addObserver:self selector:@selector(getTransformRotationAngle)
     name:UIDeviceOrientationDidChangeNotification
     object:[UIDevice currentDevice]];
}

- (void) initGestureSlider {
    CGSize screenSize = [[UIScreen mainScreen] bounds].size;
    CGRect frame = CGRectMake(screenSize.height / 2 - 80, 20, 160.0, 32.0);
    UISlider *slider = [[UISlider alloc] initWithFrame:frame];
    [slider setBackgroundColor:[UIColor colorWithRed:62.0 / 255.0f green:62.0 / 255.0f blue:62.0 / 255.0f alpha:0.50f]];
    [slider setThumbImage:[UIImage new] forState:UIControlStateNormal];
    UIImage *minimumImage = [[UIImage imageNamed:@"volume.png"] stretchableImageWithLeftCapWidth:14.0 topCapHeight:0.0];
    UIImage *maximumImage = [[UIImage imageNamed:@"maximum_image.png"] stretchableImageWithLeftCapWidth:14.0 topCapHeight:0.0];
    [slider setMinimumValueImage: minimumImage];
    [slider setMaximumValueImage: maximumImage];
    [slider setMinimumTrackImage:[UIImage imageNamed:@"progress_gray_mid.png"] forState:UIControlStateNormal];
    slider.minimumValue = 0.0;
    slider.maximumValue = 1;
    slider.layer.cornerRadius = 18;
    slider.continuous = YES;
    self.gestureSlider = slider;
    [self.rootView addSubview: self.gestureSlider];
}


- (void)expand
{
    if (!self.lockBtn) {
        [self initLockBtns];
    }
    if (!self.gestureSlider) {
        [self initGestureSlider];
    }
    self.fullscreen = YES;
    self.gestureSlider.hidden = YES;
    [self.rootView bringSubviewToFront:self.speedBar];
    [self.rootView bringSubviewToFront:self.lockBtn];
    [self.rootView bringSubviewToFront:self.releaseBtn];
    [self.rootView bringSubviewToFront:self.releaseBtn2];
    [self.rootView bringSubviewToFront: self.gestureSlider];
    [self showToolbar: YES];
//    [self setRateBtnState];
}

- (void)shrink
{
    self.fullscreen = NO;
    self.lockScreen = NO;
    [self showToolbar: NO];
    [[UIApplication sharedApplication] setStatusBarHidden:NO withAnimation:UIStatusBarAnimationNone];
    [[UIApplication sharedApplication] setStatusBarOrientation:UIInterfaceOrientationPortrait animated:NO];
}

- (void)seekTo:(float)currentTime
{
    self.player.currentTime = currentTime;
    self.toolbar.currentTime = currentTime;
}

#pragma mark - RCTMediaPlayerDelegate

- (void)OnLoadStart:(NSDictionary*)info
{
    if (self.onOMVideoLoadStart)
    {
        self.onOMVideoLoadStart(info);
    }
}

- (void)OnLoad:(NSDictionary*)info
{
    if (self.onOMVideoLoad)
    {
        self.onOMVideoLoad (info);
    }

    self.toolbar.totalTime = [[info valueForKey:@"duration"] floatValue];
}

- (void)OnLoadStalled
{
    if (self.onOMVideoLoadStalled)
    {
        self.onOMVideoLoadStalled(@{});
    }
}

- (void)OnLoadResume
{
    if (self.onOMVideoLoadResume)
    {
        self.onOMVideoLoadResume(@{});
    }
}

- (void)OnError:(NSDictionary*)info
{
    if (self.onOMVideoError)
    {
        self.onOMVideoError(info);
    }
}

- (void)OnProgress:(NSDictionary*)info
{
    if (self.onOMVideoProgress)
    {
        self.onOMVideoProgress(info);
    }

    self.toolbar.currentTime = [[info valueForKey:@"currentTime"] floatValue];
}

- (void)OnSeek:(NSDictionary*)info
{
    if (self.onOMVideoSeek)
    {
        self.onOMVideoSeek(info);
    }
}

- (void)OnEnd
{
    if (self.onOMVideoEnd)
    {
        self.onOMVideoEnd(@{});
    }

    if (self.orientation) {
        [self sendScreenOrientationToRN];
    }
    self.toolbar.currentTime = 0;
    self.toolbar.paused = self.player.paused;
    [self removePlayerTimer];
}

- (void)OnReayForPlay
{
    if (self.onOMReadyForDisplay)
    {
        self.onOMReadyForDisplay(@{});
    }

    [self showToolbar: YES];
}

- (void)OnPlaybackStalled
{
    if (self.onOMPlaybackStalled)
    {
        self.onOMPlaybackStalled(@{});
    }

    self.toolbar.paused = YES;
}

- (void)OnPlaybackResume
{
    if (self.onOMPlaybackResume)
    {
        self.onOMPlaybackResume(@{});
    }

    self.toolbar.paused = NO;
}

- (void)OnPlaybackRateChange:(NSDictionary*)info
{
    if (self.onOMPlaybackRateChange)
    {
        self.onOMPlaybackRateChange(info);
    }
}

- (void)OnOrientationChange:(NSDictionary*)info {
    if (self.onOMVideoFullscreenOrientationChange)
    {
        self.onOMVideoFullscreenOrientationChange(info);
    }
}

@end
