//
//  OnlineLearningDetailViewController.m
//  Lighting
//
//  Created by 曹云霄 on 2016/11/25.
//  Copyright © 2016年 上海勾芒科技有限公司. All rights reserved.
//

#import "OnlineLearningDetailViewController.h"
#import "VideoHelperViewController.h"
#import "VideoListViewController.h"
#import "VideoDetailViewController.h"
#import "CustomWKWebViewController.h"
#import "LearningCompleteViewController.h"
#import "AssessmentViewController.h"


@interface OnlineLearningDetailViewController ()<SelectStudyItemDelegate,VideoPlayerDelegate,BeginAssessmentDelegate,InspectionStateDelegate>

/**
 学习数据
 */
@property (nonatomic,strong) StudyTaskResponse *studyResult;
@property (nonatomic,strong) WYPopoverController *settingsPopoverController;

@end

@implementation OnlineLearningDetailViewController


#pragma mark -渲染完成
- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    self.navigationController.fd_fullscreenPopGestureRecognizer.enabled = NO;
    if ([self.navigationController respondsToSelector:@selector(interactivePopGestureRecognizer)]) {
        self.navigationController.interactivePopGestureRecognizer.enabled = NO;
    }
}

#pragma mark -视图即将消失
- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    self.navigationController.fd_fullscreenPopGestureRecognizer.enabled = YES;
    if ([self.navigationController respondsToSelector:@selector(interactivePopGestureRecognizer)]) {
        self.navigationController.interactivePopGestureRecognizer.enabled = YES;
    }
    //记录播放时间
    VideoHelperViewController *videoVc = [self.childViewControllers firstObject];
    if (videoVc.learningItem) {
        double currentTime = [videoVc getCurrentPlayingTime];
        double totalTime = videoVc.playerItem.duration.value/videoVc.playerItem.duration.timescale;
        [self switchVideoRecordPlayTime:videoVc.learningItem.attachment withPlayTime:currentTime withPlayPercent:currentTime/totalTime];
    }
    [videoVc stopPlay];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self addChildViewController];
    [self listeningHomeButton];
    [self getStudyItemDetailAction];
}

#pragma mark - 添加子控制器
- (void)addChildViewController
{
    //播放窗口
    VideoHelperViewController *videoWindow = [[[self class] getLearningCenterStoryboardClass] instantiateViewControllerWithIdentifier:@"VideoHelperViewController"];
    videoWindow.delegate = self;
    [self addChildViewController:videoWindow];
    [self.view addSubview:videoWindow.view];
    //播放简介
    VideoDetailViewController *playDetail = [[[self class] getLearningCenterStoryboardClass] instantiateViewControllerWithIdentifier:@"VideoDetailViewController"];
    [self addChildViewController:playDetail];
    [self.view addSubview:playDetail.view];
    //播放列表
    VideoListViewController *playList = [[[self class] getLearningCenterStoryboardClass] instantiateViewControllerWithIdentifier:@"VideoListViewController"];
    playList.studyItemTitle = self.studyTypeEntity.name;
    playList.delegate = self;
    videoWindow.progressDelegate = playList;
    [self addChildViewController:playList];
    [self.view addSubview:playList.view];
    __weak typeof(videoWindow) weakVideWindow = videoWindow;
    //全屏
    WS(weakSelf);
    [videoWindow setZoomButtonClickBlock:^(BOOL boolValue) {
        if (boolValue) {
            [SHARED_APPDELEGATE.window addSubview:weakVideWindow.view];
            [UIView animateWithDuration:0.2 animations:^{
                weakVideWindow.view.frame = [UIScreen mainScreen].bounds;
                weakVideWindow.playerLayer.frame = [UIScreen mainScreen].bounds;
            }];
        }else{
            [weakSelf.view insertSubview:weakVideWindow.view atIndex:0];
            [UIView animateWithDuration:0.2 animations:^{
                weakVideWindow.view.frame = CGRectMake(0, NavigationHeight, ScreenWidth*2/3, ScreenHeight/2);
                weakVideWindow.playerLayer.frame = CGRectMake(0, 0, ScreenWidth*2/3, ScreenHeight/2);
            }completion:nil];
        }
    }];
    videoWindow.view.frame = CGRectMake(0,NavigationHeight, ScreenWidth*2/3, ScreenHeight/2);
    playList.view.frame = CGRectMake(0, 64,ScreenWidth, ScreenHeight-64);
    playDetail.view.frame = CGRectMake(0, ScreenHeight/2+NavigationHeight, ScreenWidth*2/3, ScreenHeight/2-NavigationHeight);
}

#pragma mark - 监听Home键
- (void)listeningHomeButton
{
    //监听是否触发home键挂起程序.
    [Notification addObserver:self selector:@selector(applicationWillResignActive:)name:UIApplicationWillResignActiveNotification object:nil];
    //监听是否重新进入程序程序.
    [Notification addObserver:self selector:@selector(applicationDidBecomeActive:)name:UIApplicationDidBecomeActiveNotification object:nil];
}

#pragma mark - 进入后台
- (void)applicationWillResignActive:(NSNotification *)notification
{
    printf("触发home按下\n");
    //记录播放时间
    VideoHelperViewController *videoVc = [self.childViewControllers firstObject];
    if (videoVc.learningItem) {
        double currentTime = [videoVc getCurrentPlayingTime];
        double totalTime = videoVc.playerItem.duration.value/videoVc.playerItem.duration.timescale;
        [self switchVideoRecordPlayTime:videoVc.learningItem.attachment withPlayTime:currentTime withPlayPercent:currentTime/totalTime];
    }
}

#pragma mark - 进入前台
- (void)applicationDidBecomeActive:(NSNotification *)notification
{
    printf("重新进来后响应\n");
}

#pragma mark - 获取学习项详情
- (void)getStudyItemDetailAction
{
    WS(weakSelf);
    StudyTaskCondition *studyListModel = [[StudyTaskCondition alloc]init];
    studyListModel.employeeIdEquals = [Shoppersmanager manager].shoppers.employee.fid;
    studyListModel.typeEquals = self.studyTypeEntity.fid;
    DataPage *page = [[DataPage alloc] init];
    page.page = ONE;
    page.rows = 9999;
    studyListModel.page = page;
    [XBLoadingView showHUDViewWithDefault];
    [HTTP networkRequestWithURL:SERVERREQUESTURL(STUDYLIST) withRequestType:ZERO withParameter:studyListModel withReturnValueBlock:^(id returnValue) {
        
        [XBLoadingView hideHUDViewWithDefault];
        if (RESULT(returnValue)) {
            weakSelf.studyResult = [[StudyTaskResponse alloc]initWithDictionary:RESPONSE(returnValue) error:nil];
            [weakSelf transferData:weakSelf.studyResult];
        }else {
            [XBLoadingView showHUDViewWithText:MESSAGE(returnValue)];
        }
        
    }withFailureBlock:^(NSError *error) {
        [XBLoadingView showHUDViewWithText:error.localizedDescription];
    }];
}

#pragma mark - 选中学习项
- (void)seleStudyItemCellIndex:(NSIndexPath *)indexPath
{
    //判断学习列表是否处于全屏状态，第一次选中是需要取消全屏状态
    VideoListViewController *studyListVC = self.childViewControllers[2];
    if (studyListVC.view.width == ScreenWidth) {
        [studyListVC narrowAnimation];
    }
    VideoDetailViewController *studyDetailVc = self.childViewControllers[1];
    studyDetailVc.indexPath = indexPath;
    WS(weakSelf);
    VideoHelperViewController *videoVc = [self.childViewControllers firstObject];
    RsStudyTask *studyEntity = self.studyResult.studyEntity[indexPath.section];
    CustomStudyEntity *studyList = studyEntity.studyTasks[indexPath.row];
    videoVc.indexPath = indexPath;
    [studyListVC selectedIndexPath:indexPath withIsQualified:[studyList.examResult boolValue]];
    if ([studyList.attachment.fileUrl rangeOfString:@".mp4"].location != NSNotFound) {
        //判断是否是第一次播放
        if (videoVc.learningItem) {
            double currentTime = [videoVc getCurrentPlayingTime];
            double totalTime = videoVc.playerItem.duration.value/videoVc.playerItem.duration.timescale;
            [self switchVideoRecordPlayTime:videoVc.learningItem.attachment withPlayTime:currentTime withPlayPercent:currentTime/totalTime];
        }
        videoVc.learningItem = studyList;
    }else if ([studyList.attachment.fileUrl rangeOfString:@".ppt"].location != NSNotFound) {
        
        [videoVc resetPlayer];
        CustomWKWebViewController *pptVc = [[CustomWKWebViewController alloc]init];
        pptVc.urlString = studyList.attachment.fileUrl;
        pptVc.type = Study;
        pptVc.indexPath = indexPath;
        videoVc.learningItem = nil;
        [pptVc setScrollViewEndBottomBlock:^(NSIndexPath *indexPath){
            [weakSelf dismissViewControllerAnimated:YES completion:^{
                [weakSelf videoPlayFinish:studyList withIndexPath:indexPath];
            }];
        }];
        [self presentViewController:pptVc animated:YES completion:nil];
    }
}

#pragma mark - 切换视频播放记录播放时间
- (void)switchVideoRecordPlayTime:(TOAttachmentEntity *)attachment withPlayTime:(double)playTime withPlayPercent:(double)percent
{
    TOAttachmentPlayEntity *playTimeEntity = [[TOAttachmentPlayEntity alloc] init];
    playTimeEntity.fid = attachment.entityId;
    playTimeEntity.attachmentId = attachment.fid;
    playTimeEntity.employeeId = [Shoppersmanager manager].shoppers.employee.fid;
    playTimeEntity.playTime = [NSString stringWithFormat:@"%.0lf",playTime];
    playTimeEntity.playPercent = [NSString stringWithFormat:@"%.2lf",percent];
    [HTTP networkRequestWithURL:SERVERREQUESTURL(ATTACHMENTPLAYTIME) withRequestType:ZERO withParameter:playTimeEntity withReturnValueBlock:^(id returnValue) {
        
        if (RESULT(returnValue)) {
            attachment.playTime = playTimeEntity.playTime;
            attachment.playPercent = playTimeEntity.playPercent;
        }else {
            [XBLoadingView showHUDViewWithText:MESSAGE(returnValue)];
        }
        
    } withFailureBlock:^(NSError *error) {
        [XBLoadingView showHUDViewWithText:error.localizedDescription];
    }];
}


#pragma mark - 视频播放完成
- (void)videoPlayFinish:(CustomStudyEntity *)studyEntity withIndexPath:(NSIndexPath *)indexPath
{
    WS(weakSelf);
    [self studyFinishGetIntegral:^(NSString *integral) {
        LearningCompleteViewController *assessmentVc = [[[weakSelf class] getLearningCenterStoryboardClass] instantiateViewControllerWithIdentifier:@"LearningCompleteViewController"];
        assessmentVc.delegate = weakSelf;
        assessmentVc.studyEntity = studyEntity;
        assessmentVc.integralString = integral;
        assessmentVc.indexPath = indexPath;
        assessmentVc.preferredContentSize = CGSizeMake(520, 450);
        weakSelf.settingsPopoverController = [[WYPopoverController alloc] initWithContentViewController:assessmentVc];
        weakSelf.settingsPopoverController.wantsDefaultContentAppearance = NO;
        weakSelf.settingsPopoverController.theme.fillBottomColor = [UIColor clearColor];
        weakSelf.settingsPopoverController.theme.fillTopColor = [UIColor clearColor];
        weakSelf.settingsPopoverController.theme.glossShadowColor = [UIColor clearColor];
        [weakSelf.settingsPopoverController presentPopoverAsDialogAnimated:YES
                                                               options:WYPopoverAnimationOptionFadeWithScale];
    }withStudyEntity:studyEntity];
}

#pragma mark - 学习完成获取积分
- (void)studyFinishGetIntegral:(void(^)(NSString *integral))getIntegral withStudyEntity:(CustomStudyEntity *)studuEntity
{
    dispatch_group_t group = dispatch_group_create();
    dispatch_group_enter(group);
    [XBLoadingView showHUDViewWithDefault];
    // 任务一，学习项完成
    [HTTP networkWithDictionaryRequestWithURL:[NSString stringWithFormat:SERVERREQUESTURL(FINISHSTUDY),studuEntity.fid,[Shoppersmanager manager].shoppers.employee.fid] withRequestType:ONE withParameter:nil withReturnValueBlock:^(id returnValue) {
        dispatch_group_leave(group);
        if (RESULT(returnValue)) {

        }else {
            [XBLoadingView showHUDViewWithText:MESSAGE(returnValue)];
        }
        
    } withFailureBlock:^(NSError *error) {
        dispatch_group_leave(group);
        [XBLoadingView showHUDViewWithText:error.localizedDescription];
    }];
    // 任务二，获得学习积分
    dispatch_group_enter(group);
    [HTTP networkWithDictionaryRequestWithURL:[NSString stringWithFormat:SERVERREQUESTURL(GETINTEGRAL),STUDYFINISH] withRequestType:ONE withParameter:nil withReturnValueBlock:^(id returnValue) {
        
        dispatch_group_leave(group);
        if (RESULT(returnValue)) {
            if (getIntegral) {
                getIntegral(RESPONSE(returnValue));
            }
        }else {
            [XBLoadingView showHUDViewWithText:MESSAGE(returnValue)];
        }
        
    } withFailureBlock:^(NSError *error) {
        dispatch_group_leave(group);
        [XBLoadingView showHUDViewWithText:error.localizedDescription];
    }];
    // 全部任务完成
    dispatch_group_notify(group, dispatch_get_main_queue(), ^{
        [XBLoadingView hideHUDViewWithDefault];
    });
}

#pragma mark - 开始考核
- (void)beginAssessment:(CustomStudyEntity *)studyEntity withIndexPath:(NSIndexPath *)indexPath
{
    WS(weakSelf);
    VideoHelperViewController *videoWindow = self.childViewControllers[0];
    if (videoWindow.view.height == ScreenHeight) {
        [self.view insertSubview:videoWindow.view atIndex:0];
        [UIView animateWithDuration:0.2 animations:^{
            videoWindow.view.frame = CGRectMake(0, NavigationHeight, ScreenWidth*2/3, ScreenHeight/2);
            videoWindow.playerLayer.frame = CGRectMake(0, 0, ScreenWidth*2/3, ScreenHeight/2);
        }completion:^(BOOL finished) {
            [weakSelf assessment:studyEntity.fid withIndexPath:indexPath];
        }];
    }else {
        [weakSelf assessment:studyEntity.fid withIndexPath:indexPath];
    }
}

#pragma mark - 考核
- (void)assessment:(NSString *)taskId withIndexPath:(NSIndexPath *)indexPath
{
    WS(weakSelf);
    [self.settingsPopoverController dismissPopoverAnimated:YES completion:^{
        AssessmentViewController *assessmentVc = [[[self class] getLearningCenterStoryboardClass] instantiateViewControllerWithIdentifier:@"AssessmentViewController"];
        assessmentVc.taskId = taskId;
        assessmentVc.indexPath = indexPath;
        assessmentVc.delegate = weakSelf;
        [weakSelf.navigationController pushViewController:assessmentVc animated:YES];
    }];
}

#pragma mark --- <InspectionStateDelegate>考核状态
#pragma mark -再学一遍
- (void)learningAgainButtonClick:(NSIndexPath *)indexPath
{
    VideoListViewController *studyListVC = self.childViewControllers[2];
    [studyListVC selectedIndexPath:indexPath withIsQualified:NO];
    [self seleStudyItemCellIndex:indexPath];
}

#pragma mark -考核完成
- (void)inspectionThroughAction:(NSIndexPath *)indexPath
{
    VideoListViewController *studyListVC = self.childViewControllers[2];
    [studyListVC selectedIndexPath:indexPath withIsQualified:YES];
}

#pragma mark - <VideoPlayerDelegate>
- (void)isFirstPLayOrPPTPlay:(NSIndexPath *)indexPath
{
    [self seleStudyItemCellIndex:indexPath];
}

#pragma mark - 赋值
- (void)transferData:(StudyTaskResponse *)result
{
    if (result.studyEntity.count == 0) {
        [XBLoadingView showHUDViewWithText:@"学习内容为空"];
        [self.navigationController popViewControllerAnimated:YES];
        return;
    }
    VideoListViewController *studyListVC = self.childViewControllers[2];
    studyListVC.datasArray = [NSMutableArray arrayWithArray:result.studyEntity];
    VideoDetailViewController *studyDetailsVC = self.childViewControllers[1];
    studyDetailsVC.datasArray = result.studyEntity;
    studyDetailsVC.indexPath = [NSIndexPath indexPathForRow:0 inSection:0];
}


@end
