//
//  ThroughHistoryViewController.m
//  Lighting
//
//  Created by 曹云霄 on 2017/3/6.
//  Copyright © 2017年 上海勾芒科技有限公司. All rights reserved.
//

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

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

@property (nonatomic,strong) WYPopoverController *popover;

/**
 查询model
 */
@property (nonatomic,strong) PassLevelCondition *queryModel;
/**
 闯关数据
 */
@property (nonatomic,strong) PassLevelResponse *emigratedResponse;
@property (nonatomic,strong) NSMutableArray *datasArray;

@end

@implementation ThroughHistoryViewController

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

#pragma mark -UI
- (void)uiConfigAction
{
    [self setUpBoxblurImage:self.collectionBackImageView];
    self.throughHistoryFlowLayout.itemSize = CGSizeMake(130, 150);
    self.throughHistoryFlowLayout.minimumInteritemSpacing = 30;
    self.throughHistoryFlowLayout.minimumLineSpacing = 30;
}

#pragma mark -设置刷新
- (void)setUpRefreshAction
{
    WS(weakSelf);
    MjRefreshHeaderCustom *headerRefresh = [MjRefreshHeaderCustom headerWithRefreshingBlock:^{
        self.queryModel.page.page = ONE;
        [weakSelf.throughHistoryCollectionView.mj_footer resetNoMoreData];
        [weakSelf getThroughHistoryDatasAction:YES];
    }];
    headerRefresh.stateLabel.hidden = YES;
    headerRefresh.lastUpdatedTimeLabel.hidden = YES;
    self.throughHistoryCollectionView.mj_header =headerRefresh;
    [self.throughHistoryCollectionView.mj_header beginRefreshing];
    self.throughHistoryCollectionView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        if (++ weakSelf.queryModel.page.page > weakSelf.emigratedResponse.totalpages) {
            [weakSelf.throughHistoryCollectionView.mj_footer endRefreshingWithNoMoreData];
        }else
        {
            [weakSelf getThroughHistoryDatasAction:NO];
        }
    }];
    self.throughHistoryCollectionView.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.throughHistoryCollectionView];
        if (RESULT(returnValue)) {
            if (isRefresh) {
                [weakSelf.datasArray removeAllObjects];
            }
            weakSelf.emigratedResponse = [[PassLevelResponse alloc]initWithDictionary:RESPONSE(returnValue) error:nil];
            [weakSelf.datasArray addObjectsFromArray:weakSelf.emigratedResponse.passLevelEntity];
            [weakSelf.throughHistoryCollectionView reloadData];
        }else {
            [XBLoadingView hideHUDViewWithDefault];
        }
        
    }withFailureBlock:^(NSError *error) {
        [XBLoadingView showHUDViewWithText:error.localizedDescription];
    }];
}

#pragma mark -添加模糊
- (void)setUpBoxblurImage:(UIImageView *)imageView
{
    UIBlurEffect *blurEffect = [UIBlurEffect effectWithStyle:UIBlurEffectStyleLight];
    UIVisualEffectView *effectView = [[UIVisualEffectView alloc] initWithEffect:blurEffect];
    effectView.frame = imageView.bounds;
    [imageView addSubview:effectView];
}


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

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    ThroughHistoryCollectionViewCell *throughCell = [collectionView dequeueReusableCellWithReuseIdentifier:@"ThroughHistoryCollectionViewCell" forIndexPath:indexPath];
    throughCell.entity = self.datasArray[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 - 弹出框
- (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 - 完成
- (void)finished
{
    [self.popover dismissPopoverAnimated:YES];
}

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


#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