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

#import "GMVideoPlayBackViewController.h"
#import <GMFoundation/NSObject+KeyboardAnimation.h>
#import "GMFloatWindow.h"

//#import "GMConversationDetailController.h"
//#import "Gengmei-Swift.h"
//#import "GMPlayBackController+ZoomAnimation.h"

@interface GMVideoPlayBackViewController ()<PLPlayerDelegate, GMVideoPlayBackToolBarDelegate, GMVideoInfoViewDelegate, GMPlayerDelegate, GMPlayBackWelfareViewDelegate>
@property (nonatomic, strong) GMFacePlayer  *player;
@property (nonatomic, assign) CGFloat  playerProgress;
@property (nonatomic, strong) GMView *beijingView;
@property (nonatomic, strong) GMButton *pauseBtn;
@property (nonatomic, strong) GMButton *welfareBtn;
@property (nonatomic, strong) GMButton *zoomBtn;
@property (nonatomic, strong) GMButton *closeBtn;
@property (nonatomic, strong) GMButton *clearBtn;
// 是否能暂停
@property (nonatomic, assign) BOOL isPlayerPause;
@property (nonatomic, assign) CGFloat videoTop;
@end

@implementation GMVideoPlayBackViewController

- (void)initController{
    [super initController];
    _viewModel = [[GMVideoPlayBackViewModel alloc]init];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(closePlayer) name:@"closePlayer" object:nil];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = RGBCOLOR_HEX(0x333333);
    [self setupCustomView];
    [self setupConstraints];
    __weak __typeof(self)weakSelf = self;
    
    [self.viewModel fetchPlayBackWithSuccessBlock:^(NSDictionary *responseObject) {
        weakSelf.viewModel.playBackObject = [[GMVideoPlayBackObject alloc] initWithDictionary:responseObject error:nil];
        [weakSelf updateInfoView];
        [weakSelf setupPlayer];
    } failBlock:^(NSString *message) {

    }];
    self.fd_interactivePopDisabled = YES;
    self.isPlayerPause = YES;
}

- (void)closePlayer {
    [[GMRouter sharedInstance] pushScheme:@"gengmei://gm_closePlayer"];
}

- (void)updateInfoView{
    _infoView.playBackObject = self.viewModel.playBackObject;
}

- (void)setupPlayer {
    [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:nil];
    PLPlayerOption *option = [PLPlayerOption defaultOption];
    [option setOptionValue:@10 forKey:PLPlayerOptionKeyTimeoutIntervalForMediaPackets];
    _player = [GMFacePlayer playerWithURL:[NSURL URLWithString:self.viewModel.playBackObject.videoInfo.playUrl] option:option];
    _player.delegate = self;
    _player.progressDelegate = self;
    _player.delegateQueue = dispatch_get_main_queue();
    _player.backgroundPlayEnable = YES;
    CGFloat h = MAINSCREEN_WIDTH;
    if (self.viewModel.playBackObject.videoInfo.height && self.viewModel.playBackObject.videoInfo.width) {
        h = MAINSCREEN_WIDTH * self.viewModel.playBackObject.videoInfo.height / self.viewModel.playBackObject.videoInfo.width;
    }
    self.videoTop = (MAINSCREEN_HEIGHT - h) / 2;
    if (_player.status != PLPlayerStatusError) {
        // add player view
        UIView *playerView = self.player.playerView;
        if (!playerView.superview) {
            [playerView addSubview:self.beijingView];
            [playerView addSubview:self.pauseBtn];
            #ifdef APPSTORE
                playerView.contentMode = UIViewContentModeScaleAspectFill;
            #endif
            [self.view addSubview:playerView];
            [self.view sendSubviewToBack:playerView];
            [playerView mas_makeConstraints:^(MASConstraintMaker *make) {
                make.left.right.mas_equalTo(0);
                make.top.mas_equalTo(self.videoTop);
                make.bottom.mas_equalTo(-self.videoTop);
            }];
            [self.beijingView mas_makeConstraints:^(MASConstraintMaker *make) {
                make.edges.mas_equalTo(0);
            }];
            
            [self.pauseBtn mas_makeConstraints:^(MASConstraintMaker *make) {
                make.edges.mas_equalTo(0);
            }];
        }
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(playClick)];
        [playerView addGestureRecognizer:tap];
    }
    [self startPlayer];
}

- (void)startPlayer {
    [UIApplication sharedApplication].idleTimerDisabled = YES;
    [self.player play];
    [_player addProgressObserver];
    _toolBar.processLabel.text = [NSString stringWithFormat:@"%@", [_player getMMSSFromSS:CMTimeGetSeconds(_player.totalDuration)]];
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    if ([self.viewModel.playBackObject.videoInfo.playUrl isNonEmpty]) {
        [_player resume];
    }
    self.navigationBar.hidden = YES;
}

// 离开页面必须执行cancel方法，不然生成的timer会强持有controller，页面不会释放
- (void)viewDidDisappear:(BOOL)animated{
    [super viewDidDisappear:animated];
    [_player pausePlayer];
    //离开直播间，屏幕常量需要关闭
    [UIApplication sharedApplication].idleTimerDisabled = NO;
}

- (void)setupCustomView{

    _infoView = [[GMVideoInfoView alloc]init];
    _infoView.delegate = self;
    [self.view addSubview:_infoView];

    _toolBar = [[GMVideoPlayBackToolBar alloc] init];
    _toolBar.delegate = self;
    [self.view addSubview:_toolBar];
    _toolBar.layer.cornerRadius = 5;
    _toolBar.layer.masksToBounds = YES;

    [self.view addSubview:self.welfareBtn];
    [self.view addSubview:self.zoomBtn];
    [self.view addSubview:self.closeBtn];
    [self.view addSubview:self.clearBtn];
}

- (void)setupConstraints{
    [_infoView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(OCNavigationBar.statusBarHeight + 10);
        make.left.right.mas_equalTo(0);
        make.height.mas_equalTo(135);
    }];
    
    [_toolBar mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.mas_equalTo(-UIView.safeAreaInsetsBottom - 20);
        make.left.mas_equalTo(8);
        make.right.mas_equalTo(-8);
        make.height.mas_equalTo(50);
    }];

    [_player.playerView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.mas_equalTo(0);
    }];
    
    [self.welfareBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.mas_equalTo(self.toolBar.mas_top).offset(-15);
        make.left.mas_equalTo(30);
    }];
    
    [self.zoomBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.mas_equalTo(self.toolBar.mas_top).offset(-15);
        make.right.mas_equalTo(-30);
    }];
    
    [self.closeBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(MAINSCREEN_HEIGHT * 0.035);
        make.left.mas_equalTo(MAINSCREEN_HEIGHT * 0.035);
        make.size.mas_equalTo(CGSizeMake(MAINSCREEN_HEIGHT * 0.04, MAINSCREEN_HEIGHT * 0.04));
    }];
    [self.clearBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.top.mas_equalTo(0);
        make.size.mas_equalTo(CGSizeMake(MAINSCREEN_HEIGHT * 0.13, MAINSCREEN_HEIGHT * 0.13));
    }];
}

#pragma mark - GMRoomInfoViewDelegate
- (void)videoInfoView:(GMVideoInfoView *)videoInfoView didClickCloseButton:(GMButton *)button {
    [self closePlaybackView];
}

- (void)closePlaybackView {
    [_player pauseTimer];
    [[GMRouter sharedInstance] pushScheme:@"gengmei://gm_closePlaybackView"];
}

- (void)dealloc {
    [_player stop];
}

#pragma mark - PLPlayerDelegate
- (void)player:(PLPlayer *)player statusDidChange:(PLPlayerStatus)state {

}

#pragma mark - GMPlayBackToolBarDelegate
- (void)didCilckedPlayVedio:(UIButton *)button {
    button.selected = !button.selected;
    if (button.selected) {
        [_player pausePlayer];
        _beijingView.hidden = NO;
        _pauseBtn.hidden = NO;
    } else {
        [_player resume];
        _beijingView.hidden = YES;
        _pauseBtn.hidden = YES;
    }
}

- (void)playClick {
    if (self.isPlayerPause) {
        [_player pausePlayer];
        _beijingView.hidden = NO;
        _pauseBtn.hidden = NO;
        _toolBar.playButton.selected = YES;
    }
    self.isPlayerPause = !self.zoomBtn.hidden;
}

- (void)beijingViewClick {
    [_player resume];
    _beijingView.hidden = YES;
    _pauseBtn.hidden = YES;
    _toolBar.playButton.selected = NO;
}

- (void)zoomClick {
    [self hideOtherViews];
    [[GMRouter sharedInstance] pushScheme:@"gengmei://gm_videoZoomToSmall"];

//    [[AppDelegate shareInstance].videoFloatView videoZoomToSmall];
}

- (void)welfareClick {
    _welfareView = [GMPlayBackWelfareView new];
    _welfareView.delegate = self;
    [self.view addSubview:_welfareView];
    __weak __typeof(self)weakSelf = self;
    [self.viewModel fetchPlayBackRecommendWithSuccessBlock:^(NSDictionary *responseObject) {
        weakSelf.viewModel.dataArray = [GMWelfareServiceObject arrayOfModelsFromDictionaries:responseObject[@"services"] error:nil];
        weakSelf.welfareView.dataArr = weakSelf.viewModel.dataArray;
    } failBlock:^(NSString *message) {
        
    }];
}

- (GMView *)beijingView {
    if (!_beijingView) {
        _beijingView = [[GMView alloc] initWithFrame:self.player.playerView.bounds];
        _beijingView.backgroundColor = [UIColor blackColor];
        _beijingView.alpha = 0.3;
        _beijingView.hidden = YES;
    }
    return _beijingView;
}

- (GMButton *)pauseBtn {
    if (!_pauseBtn) {
        _pauseBtn = [[GMButton alloc] init];
        [_pauseBtn setImage:[UIImage imageNamed:@"play_Back_button"] forState:UIControlStateNormal];
        [_pauseBtn setImage:[UIImage imageNamed:@"play_Back_button"] forState:UIControlStateHighlighted];
        _pauseBtn.hidden = YES;
        [_pauseBtn addTarget:self action:@selector(beijingViewClick) forControlEvents:UIControlEventTouchUpInside];
    }
    return _pauseBtn;
}

- (GMButton *)welfareBtn {
    if (!_welfareBtn) {
        _welfareBtn = [[GMButton alloc] init];
        [_welfareBtn setImage:[UIImage imageNamed:@"play_back_welfare"] forState:UIControlStateNormal];
        [_welfareBtn setImage:[UIImage imageNamed:@"play_back_welfare"] forState:UIControlStateHighlighted];
        [_welfareBtn addTarget:self action:@selector(welfareClick) forControlEvents:UIControlEventTouchUpInside];
    }
    return _welfareBtn;
}

- (GMButton *)zoomBtn {
    if (!_zoomBtn) {
        _zoomBtn = [[GMButton alloc] init];
        [_zoomBtn setImage:[UIImage imageNamed:@"play_back_suoxiao"] forState:UIControlStateNormal];
        [_zoomBtn setImage:[UIImage imageNamed:@"play_back_suoxiao"] forState:UIControlStateHighlighted];
        [_zoomBtn addTarget:self action:@selector(zoomClick) forControlEvents:UIControlEventTouchUpInside];
    }
    return _zoomBtn;
}

- (GMButton *)clearBtn {
    if (!_clearBtn) {
        _clearBtn = [[GMButton alloc] init];
        [_clearBtn addTarget:self action:@selector(closePlaybackView) forControlEvents:UIControlEventTouchUpInside];
        _clearBtn.hidden = YES;
    }
    return _clearBtn;
}

- (GMButton *)closeBtn {
    if (!_closeBtn) {
        _closeBtn = [[GMButton alloc] init];
        [_closeBtn setImage:[UIImage imageNamed:@"video_play_back"] forState:UIControlStateNormal];
        [_closeBtn setImage:[UIImage imageNamed:@"video_play_back"] forState:UIControlStateHighlighted];
        _closeBtn.hidden = YES;
    }
    return _closeBtn;
}

- (void)willChangeSliderValue {
    [_player pauseTimer];
}

- (void)finishChangeSliderValue {
    [_player seekToProgress:_playerProgress];
    [_viewModel clearData];
    [_player resumeTimer];
}

- (void)changeSliderValue:(CGFloat)value {
    _playerProgress = value;
}

#pragma mark - GMPlayerDelegate
- (void)updateBeginTimeTitle:(NSString *)title {
    _toolBar.processBeginLabel.text = title;
}

- (void)updateTotalTimeTitle:(NSString *)title {
    _toolBar.processLabel.text = title;
}

- (void)updateProgress:(CGFloat)value {
    _toolBar.processSlider.value = value;
}

#pragma mark - GMLiveWelfareViewDelegate
- (void)didSelectedWelfareView:(GMPlayBackWelfareView *)welFareView obj:(GMWelfareServiceObject *)obj {
    [self hideOtherViews];
    [[GMRouter sharedInstance] pushScheme:@"gengmei://gm_videoZoomToSmall"];

    //跳转到美购详情
    
    NSString *url = [NSString stringWithFormat:@"gengmei://service?service_id=%@", obj.serviceId];
    [[GMRouter sharedInstance] pushScheme:url];
}

#pragma mark - GMFloatWindowProtocol
- (void)hideOtherViews{
    self.toolBar.hidden = YES;
    self.infoView.hidden = YES;
    self.welfareView.hidden = YES;
    self.welfareBtn.hidden = YES;
    self.zoomBtn.hidden = YES;
    self.closeBtn.hidden = NO;
    self.clearBtn.hidden = NO;
    [_player.playerView mas_updateConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(MAINSCREEN_HEIGHT * 0.11);
        make.bottom.mas_equalTo(-MAINSCREEN_HEIGHT * 0.11);
    }];
    self.isPlayerPause = NO;
}

- (void)showOtherViews{
    self.toolBar.hidden = NO;
    self.infoView.hidden = NO;
    self.welfareView.hidden = NO;
    self.welfareBtn.hidden = NO;
    self.zoomBtn.hidden = NO;
    self.closeBtn.hidden = YES;
    self.clearBtn.hidden = YES;
    [_player.playerView mas_updateConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.videoTop);
        make.bottom.mas_equalTo(-self.videoTop);
    }];
}

@end
