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

#import "EmigratedMainViewController.h"
#import "InstructionsViewController.h"
#import "AnswerViewController.h"
#import "ThroughHistoryCollectionViewCell.h"
#import "EmigratedFinishViewController.h"
#import "ThroughHistoryViewController.h"

@interface EmigratedMainViewController ()<WYPopoverControllerDelegate,DismissDelegate,UICollectionViewDelegate,UICollectionViewDataSource,CompeteDelegate>

@property (nonatomic,strong) WYPopoverController *popover;

/**
 闯关数据
 */
@property (nonatomic,strong) PassLevelResponse *emigratedResponse;

@end

@implementation EmigratedMainViewController


- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self uiConfigAction];
    [self getThroughHistoryDatasAction];
}

#pragma mark -UI
- (void)uiConfigAction
{
    self.throughHistoryFlowLayout.itemSize = CGSizeMake(130, 150);
    self.throughHistoryCollectionView.alwaysBounceVertical = YES;
    self.throughHistoryFlowLayout.minimumInteritemSpacing = 30;
    self.throughHistoryCollectionView.alpha = 0;
}

#pragma mark - 获取闯关信息
- (void)getThroughHistoryDatasAction
{
    WS(weakSelf);
    PassLevelCondition *emigrated = [[PassLevelCondition alloc]init];
    emigrated.validEquals = YES;
    DataPage *page = [[DataPage alloc]init];
    page.page = ONE;
    page.rows = KROWS;
    emigrated.page = page;
    [XBLoadingView showHUDViewWithDefault];;
    [HTTP networkRequestWithURL:SERVERREQUESTURL(THROUGHLIST) withRequestType:ZERO withParameter:emigrated withReturnValueBlock:^(id returnValue) {
        
        [XBLoadingView hideHUDViewWithDefault];
        if (RESULT(returnValue)) {
            weakSelf.emigratedResponse = [[PassLevelResponse alloc]initWithDictionary:RESPONSE(returnValue) error:nil];
            [weakSelf.throughHistoryCollectionView reloadData];
        }else {
            [XBLoadingView hideHUDViewWithDefault];
        }
        
    }withFailureBlock:^(NSError *error) {
        [XBLoadingView showHUDViewWithText:error.localizedDescription];
    }];
}

#pragma mark - 开始
- (IBAction)beginButtonClickAction:(UIButton *)sender {
    
    [UIView animateWithDuration:0.2 animations:^{
        sender.alpha = 0;
        self.throughHistoryCollectionView.alpha = 1;
    }];
}


#pragma mark -<UICollectionViewDelegate,UICollectionViewDataSource>
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return self.emigratedResponse.passLevelEntity.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    ThroughHistoryCollectionViewCell *throughCell = [collectionView dequeueReusableCellWithReuseIdentifier:@"ThroughHistoryCollectionViewCell" forIndexPath:indexPath];
    throughCell.entity = self.emigratedResponse.passLevelEntity[indexPath.item];
    return throughCell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    TOPassLevelEntity *entity = self.emigratedResponse.passLevelEntity[indexPath.item];
    [self judgePlanState:entity];
}

#pragma mark -判断任务状态
- (void)judgePlanState:(TOPassLevelEntity *)entity
{
    if ([entity.passResult isEqualToString:@"0"]) {
        AnswerViewController *answer = [[[self class] getLearningCenterStoryboardClass] instantiateViewControllerWithIdentifier:@"AnswerViewController"];
        answer.delegate = self;
        answer.passLevelId = entity.fid;
        answer.preferredContentSize = CGSizeMake(520, 400);
        [self showPopoverView:answer];
        
    }else {
        WS(weakSelf);
        [self getPasslevelResult:entity finish:^(TOPassLevelResultEntity *resultEntity,NSString *integration) {
            EmigratedFinishViewController *resultVc = [[[weakSelf class] getLearningCenterStoryboardClass] instantiateViewControllerWithIdentifier:@"EmigratedFinishViewController"];
            resultVc.delegate = weakSelf;
            resultVc.state = [resultEntity.passResult integerValue];
            resultVc.score = [resultEntity.grade stringValue];
            resultVc.integral = integration;
            resultVc.preferredContentSize = CGSizeMake(520, 400);
            [weakSelf showPopoverView:resultVc];
        }];
    }
}

#pragma mark -获取闯关成功信息
- (void)getPasslevelResult:(TOPassLevelEntity *)entity finish:(void(^)(TOPassLevelResultEntity *entity,NSString *integral))result
{
    __block TOPassLevelResultEntity *resulrEntity;
    __block NSString *integral = nil;
    [XBLoadingView showHUDViewWithDefault];
    dispatch_group_t group = dispatch_group_create();
    dispatch_group_enter(group);
    [HTTP networkWithDictionaryRequestWithURL:[NSString stringWithFormat:SERVERREQUESTURL(PASSLEVERESULT),entity.fid] withRequestType:NetworkRequestWithGET withParameter:nil withReturnValueBlock:^(id returnValue) {
        
        dispatch_group_leave(group);
        [XBLoadingView hideHUDViewWithDefault];
        if (RESULT(returnValue)) {
            resulrEntity = [[TOPassLevelResultEntity alloc] initWithDictionary:RESPONSE(response) error:nil];
        }else {
            [XBLoadingView showHUDViewWithText:returnValue[@"message"]];
        }
        
    } withFailureBlock:^(NSError *error) {
        [XBLoadingView showHUDViewWithText:error.localizedDescription];
    }];
    dispatch_group_enter(group);
    NSString *url = [NSString stringWithFormat:SERVERREQUESTURL(GETINTEGRAL),RECRUITTHROUGH];
    [HTTP networkWithDictionaryRequestWithURL:url withRequestType:ONE withParameter:nil withReturnValueBlock:^(id returnValue) {
        dispatch_group_leave(group);
        [XBLoadingView hideHUDViewWithDefault];
        if (RESULT(returnValue)) {
            
              integral = [NSString stringWithFormat:@"+%@",RESPONSE(returnValue)];
            
        }else {
            [XBLoadingView showHUDViewWithText:returnValue[@"message"]];
        }
        
    } withFailureBlock:^(NSError *error) {
        [XBLoadingView showHUDViewWithText:error.localizedDescription];
    }];
    
    dispatch_group_notify(group, dispatch_get_main_queue(), ^{
        result(resulrEntity,integral);
    });
}


#pragma mark - <DismissDelegate>
#pragma mark - 做题完成
- (void)dismissController:(BOOL)animationed
{
    [self.popover dismissPopoverAnimated:animationed];
}

#pragma mark - 闯关完成
- (void)emigratedFinish
{
    [self getThroughHistoryDatasAction];
}

#pragma mark - 完成
- (void)finished
{
    [self.popover dismissPopoverAnimated:YES];
}

#pragma mark - 闯关说明
- (IBAction)instructionsButtonClickAction:(UIButton *)sender {
    
    InstructionsViewController *instruction = [[[self class] getLearningCenterStoryboardClass] instantiateViewControllerWithIdentifier:@"InstructionsViewController"];
    WS(weakSelf);
    [instruction setDismissSyntonyBlock:^{
        [weakSelf.popover dismissPopoverAnimated:YES];
    }];
    instruction.preferredContentSize = CGSizeMake(ScreenWidth/2, ScreenHeight/2);
    [self showPopoverView:instruction];
}

#pragma mark - 弹出框
- (void)showPopoverView:(BaseViewController *)controller
{
    self.popover = [[WYPopoverController alloc] initWithContentViewController:controller];
    self.popover.theme.fillBottomColor = [UIColor clearColor];
    self.popover.theme.fillTopColor = [UIColor clearColor];
    self.popover.theme.glossShadowColor = [UIColor clearColor];
    self.popover.delegate = self;
    [self.popover presentPopoverAsDialogAnimated:YES options:WYPopoverAnimationOptionFadeWithScale];
}

#pragma mark - 点击空白禁止收起
- (BOOL)popoverControllerShouldDismissPopover:(WYPopoverController *)popoverController
{
    return NO;
}

@end