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

#import "BreakThroughViewController.h"
#import "InstructionsViewController.h"
#import "AnswerViewController.h"
#import "BreakThroughFinishViewController.h"
#import "BreakThroughTableViewCell.h"
#import "StartBreakThroughViewController.h"

@interface BreakThroughViewController ()<WYPopoverControllerDelegate,DismissDelegate,UITableViewDelegate,UITableViewDataSource,CompeteDelegate,StartBreakThroughDelegate>

@property (nonatomic,strong) WYPopoverController *popover;

/**
 查询model
 */
@property (nonatomic,strong) PassLevelCondition *queryModel;
/**
 数据源
 */
@property (nonatomic,strong) NSMutableArray *datasArray;

/**
 选中关卡
 */
@property (nonatomic,assign) NSInteger selectedIndex;


@end

@implementation BreakThroughViewController


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

#pragma mark -UI
- (void)uiConfigAction
{
    self.tableView.backgroundView = [[UIImageView alloc] initWithImage:TCImage(@"confirmBack")];
}

#pragma mark -加载数据
- (void)loadWebDataSource
{
    WS(weakSelf);
    if (self.pullPageIndex == ONE) {
        [self.datasArray removeAllObjects];
    }
    self.queryModel.page.page = self.pullPageIndex;
    [self getThroughHistoryDatasActionCompleted:^(PassLevelResponse *result) {
        if (weakSelf.pullPageIndex >= result.totalpages) {
            [weakSelf endRefresh:EndRefreshNotData];
        }else {
            [weakSelf endRefresh:EndRefreshDefault];
        }
    }];
}


#pragma mark - 获取闯关信息
- (void)getThroughHistoryDatasActionCompleted:(void(^)(PassLevelResponse *result))completed
{
    WS(weakSelf);
    [HTTP networkRequestWithURL:SERVERREQUESTURL(THROUGHLIST) withRequestType:ZERO withParameter:self.queryModel withReturnValueBlock:^(id returnValue) {
        if (RESULT(returnValue)) {
            PassLevelResponse *emigratedResponse = [[PassLevelResponse alloc]initWithDictionary:RESPONSE(returnValue) error:nil];
            completed(emigratedResponse);
            [weakSelf.datasArray addObjectsFromArray:emigratedResponse.passLevelEntity];
            [weakSelf.tableView reloadData];
        }else {
            [XBLoadingView hideHUDViewWithDefault];
        }
        
    }withFailureBlock:^(NSError *error) {
        [weakSelf endRefresh:EndRefreshDefault];
        [XBLoadingView showHUDViewWithText:error.localizedDescription];
    }];
}


#pragma mark -<UITableViewDelegate,UITableViewDataSource>
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.datasArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    BreakThroughTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"BreakThroughTableViewCell" forIndexPath:indexPath];
    cell.entity = self.datasArray[indexPath.row];
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    self.selectedIndex = indexPath.row;
    TOPassLevelEntity *entity = self.datasArray[indexPath.item];
    [self judgePlanState:entity];
}

#pragma mark -判断任务状态
- (void)judgePlanState:(TOPassLevelEntity *)entity
{
    if ([entity.passResult isEqualToString:@"0"] && !entity.residue) {//失败
        
    }else if ([entity.passResult isEqualToString:@"1"]){//成功
        WS(weakSelf);
        [self getPasslevelResult:entity finish:^(TOPassLevelResultEntity *resultEntity,NSString *integration) {
            BreakThroughFinishViewController *resultVc = [BreakThroughFinishViewController viewControllerWithStoryBoardType:STORYBOARD_TYPE_LEARNINGCENTER];
            resultVc.delegate = weakSelf;
            resultVc.state = [resultEntity.passResult integerValue];
            resultVc.score = [resultEntity.grade stringValue];
            resultVc.integral = integration;
            resultVc.preferredContentSize = CGSizeMake(520, 400);
            [weakSelf showPopoverView:resultVc];
        }];
    }else if ([entity.passResult isEqualToString:@"2"]){//提交
        
    }else {//未闯关
        StartBreakThroughViewController *startBreakThrough = [StartBreakThroughViewController viewControllerWithStoryBoardType:STORYBOARD_TYPE_LEARNINGCENTER];
        startBreakThrough.opportunityNumber = entity.residue;
        startBreakThrough.delegate = self;
        startBreakThrough.opportunityNumber = entity.residue;
        startBreakThrough.passResult = entity.passResult;
        startBreakThrough.preferredContentSize = CGSizeMake(520, 400);
        [self showPopoverView:startBreakThrough];
    }
}

#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:GET 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:MESSAGE(returnValue)];
        }
        
    } 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:MESSAGE(returnValue)];
        }
        
    } 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:(NSString *)passResult
{
    TOPassLevelEntity *entity = self.datasArray[self.selectedIndex];
    entity.passResult = passResult;
    //闯关失败
    if ([passResult isEqualToString:@"0"]) {
        //扣除一次闯关机会
        if (entity.residue > 0) {
            entity.residue -= 1;
        }
    }
    [self.tableView reloadRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:self.selectedIndex inSection:0]] withRowAnimation:UITableViewRowAnimationFade];
}

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

#pragma mark -<StartBreakThroughDelegate>
- (void)startAnswerTheQuestions
{
    TOPassLevelEntity *entity = self.datasArray[self.selectedIndex];
    AnswerViewController *answer = [AnswerViewController viewControllerWithStoryBoardType:STORYBOARD_TYPE_LEARNINGCENTER];
    answer.delegate = self;
    answer.entity = entity;
    answer.preferredContentSize = CGSizeMake(520, 400);
    [self showPopoverView:answer];
}

- (void)closeController
{
    [self.popover dismissPopoverAnimated:YES];
}

#pragma mark - 闯关说明
- (IBAction)instructionsButtonClickAction:(UIButton *)sender {
    
    InstructionsViewController *instruction = [InstructionsViewController viewControllerWithStoryBoardType:STORYBOARD_TYPE_LEARNINGCENTER];
    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;
}

#pragma mark -lazy
- (NSMutableArray *)datasArray
{
    if (!_datasArray) {
        _datasArray = [NSMutableArray array];
    }
    return _datasArray;
}

- (PassLevelCondition *)queryModel
{
    if (!_queryModel) {
        _queryModel = [[PassLevelCondition alloc] init];
        _queryModel.validEquals = YES;
        DataPage *page = [[DataPage alloc]init];
        page.page = ONE;
        page.rows = KROWS;
        _queryModel.page = page;
    }
    return _queryModel;
}







@end
