//
//  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;

/**
 闯关数据
 */
@property (nonatomic,strong) PassLevelResponse *emigratedResponse;
/**
 查询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];
    [self setUpRefreshAction];
}

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

#pragma mark -设置刷新
- (void)setUpRefreshAction
{
    WS(weakSelf);
    MjRefreshHeaderCustom *headerRefresh = [MjRefreshHeaderCustom headerWithRefreshingBlock:^{
        weakSelf.queryModel.page.page = ONE;
        [weakSelf.emigratedTableView.mj_footer resetNoMoreData];
        [weakSelf getThroughHistoryDatasAction:YES];
    }];
    headerRefresh.stateLabel.hidden = YES;
    headerRefresh.lastUpdatedTimeLabel.hidden = YES;
    self.emigratedTableView.mj_header =headerRefresh;
    [self.emigratedTableView.mj_header beginRefreshing];
    self.emigratedTableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        if (++ weakSelf.queryModel.page.page > weakSelf.emigratedResponse.totalpages) {
            [weakSelf.emigratedTableView.mj_footer endRefreshingWithNoMoreData];
        }else
        {
            [weakSelf getThroughHistoryDatasAction:NO];
        }
    }];
    self.emigratedTableView.mj_footer.automaticallyHidden = YES;
}

#pragma mark - 获取闯关信息
- (void)getThroughHistoryDatasAction:(BOOL)isRefresh
{
    WS(weakSelf);
    [XBLoadingView showHUDViewWithDefault];;
    [HTTP networkRequestWithURL:SERVERREQUESTURL(THROUGHLIST) withRequestType:ZERO withParameter:self.queryModel withReturnValueBlock:^(id returnValue) {
        
        [XBLoadingView hideHUDViewWithDefault];
        [weakSelf endRefreshingForTableView:weakSelf.emigratedTableView];
        if (RESULT(returnValue)) {
            if (isRefresh) {
                [weakSelf.datasArray removeAllObjects];
            }
            weakSelf.emigratedResponse = [[PassLevelResponse alloc]initWithDictionary:RESPONSE(returnValue) error:nil];
            [weakSelf.datasArray addObjectsFromArray:weakSelf.emigratedResponse.passLevelEntity];
            [weakSelf.emigratedTableView reloadData];
        }else {
            [XBLoadingView hideHUDViewWithDefault];
        }
        
    }withFailureBlock:^(NSError *error) {
        [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 = [[[weakSelf class] getLearningCenterStoryboardClass] instantiateViewControllerWithIdentifier:@"BreakThroughFinishViewController"];
            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 = [[[self class] getLearningCenterStoryboardClass] instantiateViewControllerWithIdentifier:@"StartBreakThroughViewController"];
        startBreakThrough.opportunityNumber = [NSString stringWithFormat:@"%ld",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.emigratedTableView 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 = [[[self class] getLearningCenterStoryboardClass] instantiateViewControllerWithIdentifier:@"AnswerViewController"];
    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 = [[[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;
}

#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
