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

#import "AnswerViewController.h"
#import "AssessmentShortAnswerTableViewCell.h"
#import "AssessmentHeaderView.h"
#import "AssessmentTableViewCell.h"
#import "AssessmentShortAnswerTableViewCell.h"
#import "BreakThroughFinishViewController.h"


@interface AnswerViewController ()<UITableViewDelegate,UITableViewDataSource,WYPopoverControllerDelegate,CompeteDelegate>


@property (nonatomic,strong) WYPopoverController *popover;

/**
 闯关详情
 */
@property (nonatomic,strong) TOPassLevelEntity *emigrated;

/**
 当前加载section
 */
@property (nonatomic,assign) NSInteger sectionPage;

@end

@implementation AnswerViewController

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

#pragma mark - UI
- (void)uiConfigAction
{
    self.answerTableView.backgroundColor = [UIColor clearColor];
}

#pragma mark - 查询题型
- (void)getPassLevelDeltails
{
    WS(weakSelf);
    [XBLoadingView showHUDViewWithDefault];
    [HTTP networkWithDictionaryRequestWithURL:[NSString stringWithFormat:SERVERREQUESTURL(GETPASSLEVELDETAILS),self.entity.fid] withRequestType:ONE withParameter:nil withReturnValueBlock:^(id returnValue) {
        [XBLoadingView hideHUDViewWithDefault];
        if (RESULT(returnValue)) {
            weakSelf.emigrated = [[TOPassLevelEntity alloc] initWithDictionary:RESPONSE(returnValue) error:nil];
            [weakSelf.answerTableView reloadData];
        }else {
            [XBLoadingView showHUDViewWithText:MESSAGE(returnValue)];
        }
        
    } withFailureBlock:^(NSError *error) {
        [XBLoadingView showHUDViewWithText:error.localizedDescription];
    }];
}

#pragma mark - <UITableViewDelegate,UITableViewDataSource>
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    CustomTOPassLevelTopicEntity *entity = self.emigrated.topics[self.sectionPage];
    if ([entity.topicType isEqualToString:PASSLEVELTOPICTYPE_GAPFILLING] || [entity.topicType isEqualToString:PASSLEVELTOPICTYPE_SHORTANSWER]) {
        AssessmentShortAnswerTableViewCell *shortAnswerCell = [tableView dequeueReusableCellWithIdentifier:@"AssessmentShortAnswerTableViewCell" forIndexPath:indexPath];
        shortAnswerCell.entity = entity;
        shortAnswerCell.backgroundColor = [UIColor clearColor];
        return shortAnswerCell;
    }
    AssessmentTableViewCell *assessmentCell = [tableView dequeueReusableCellWithIdentifier:@"AssessmentTableViewCell" forIndexPath:indexPath];
    assessmentCell.backgroundColor = [UIColor clearColor];
    assessmentCell.emigratedEntity = entity.options[indexPath.row];
    return assessmentCell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    CustomTOPassLevelTopicEntity *entity = self.emigrated.topics[self.sectionPage];
    return entity.titleHeight;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    CustomTOPassLevelTopicEntity *entity = self.emigrated.topics[self.sectionPage];
    if (entity.options.count) {
        CustomTOPassLevelTopicOptionEntity *answer = entity.options[indexPath.row];
        return answer.answerHeight;
    }
    return 200;
}

- (void)tableView:(UITableView *)tableView didEndDisplayingCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath*)indexPath
{
    if ([cell isKindOfClass:[AssessmentShortAnswerTableViewCell class]]) {
        AssessmentShortAnswerTableViewCell *shortAnswerCell = (AssessmentShortAnswerTableViewCell *)cell;
        shortAnswerCell.shortAnswerTextView.text = nil;
    }
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return ONE;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    CustomTOPassLevelTopicEntity *entity = self.emigrated.topics[self.sectionPage];
    if ([entity.topicType isEqualToString:PASSLEVELTOPICTYPE_GAPFILLING] || [entity.topicType isEqualToString:PASSLEVELTOPICTYPE_SHORTANSWER]) {
        return ONE;
    }
    return entity.options.count;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    AssessmentHeaderView *headerView = [tableView dequeueReusableCellWithIdentifier:@"AssessmentHeaderView"];
    headerView.emigratedEntity = self.emigrated.topics[self.sectionPage];
    return headerView.contentView;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    CustomTOPassLevelTopicEntity *entitys = self.emigrated.topics[self.sectionPage];
    if ([entitys.topicType isEqualToString:STUDYTOPICTYPE_SINGLE] || [entitys.topicType isEqualToString:STUDYTOPICTYPE_TRUEORFALSE]) {
        for (int i=0; i<entitys.options.count; i++) {
            CustomTOPassLevelTopicOptionEntity *entity = entitys.options[i];
            if (i == indexPath.row) {
                entity.isSelected = !entity.isSelected;
            }else {
                entity.isSelected = NO;
            }
       }
    }else if ([entitys.topicType isEqualToString:STUDYTOPICTYPE_MULTIPLE]) {
        CustomTOPassLevelTopicOptionEntity *answer = entitys.options[indexPath.row];
        answer.isSelected = !answer.isSelected;
    }
    [self.answerTableView reloadData];
}

#pragma mark - 下一步<最后一道题自动提交>
- (IBAction)nextButtonClickAction:(UIButton *)sender {

    if (self.sectionPage == self.emigrated.topics.count-1) {
        [self submitAnswer];
    }else {
        if (![self judgeIsAnswer]) {
            [XBLoadingView showHUDViewWithText:@"答案不能为空"];return;
        }
        self.sectionPage += ONE;
        [self.answerTableView reloadData];
    }
}

#pragma mark - 判断是否已回答
- (BOOL)judgeIsAnswer
{
    CustomTOPassLevelTopicEntity *entitys = self.emigrated.topics[self.sectionPage];
    //简答题/填空题
    if ([entitys.topicType isEqualToString:PASSLEVELTOPICTYPE_SHORTANSWER] || [entitys.topicType isEqualToString:PASSLEVELTOPICTYPE_GAPFILLING]) {
        return ![[self class] isBlankString:entitys.answer];
    }
    //单选、多选、判断
    for (CustomTOPassLevelTopicOptionEntity *answer in entitys.options) {
        if (answer.isSelected) {
            return YES;
        }
    }
    return NO;
}

#pragma mark - 提交答案
- (void)submitAnswer
{
    if ([self.delegate respondsToSelector:@selector(dismissController:)]) {
        [self.delegate dismissController:NO];
    }
    TOPassLevelResultEntity *studyResult = [[TOPassLevelResultEntity alloc]init];
    studyResult.passLevelId = self.entity.fid;
    studyResult.submitTime = [[self class] getTimeby:0];
    studyResult.employeeId = [Shoppersmanager manager].shoppers.employee.fid;
    NSArray *answerArray = self.emigrated.topics;
    NSMutableArray *submitAnswerArray = [NSMutableArray array];
    //判断考核结果
    NSInteger allScore = 0;//总分
    for (CustomTOPassLevelTopicEntity *topicEntity in answerArray) {
        
        TOPassLevelResultDetailEntity *resultEntity = [[TOPassLevelResultDetailEntity alloc] init];
        resultEntity.topicId = topicEntity.fid;
        //多选
        if ([topicEntity.topicType isEqualToString:STUDYTOPICTYPE_MULTIPLE]) {
            NSMutableString *answers = [[NSMutableString alloc] init];
            for (CustomTOPassLevelTopicOptionEntity *entity in topicEntity.options) {
                if (entity.isSelected == YES) {
                    [answers appendFormat:@"%@,",entity.value];
                }
            }
            resultEntity.answer = answers;
            //得分
            NSArray *answersArray = [topicEntity.answer componentsSeparatedByString:@","];
            NSInteger answerNumber = 0;
            for (NSString *answer in answersArray) {
                for (CustomTOStudyTopicOptionEntity *entity in topicEntity.options) {
                    if ([answer isEqualToString:entity.value] && entity.isSelected) {
                        answerNumber += 1;
                    }
                }
            }
            if (answerNumber == answersArray.count) {
                resultEntity.grade = topicEntity.grade;
                allScore += [topicEntity.grade integerValue];
            }else {
                resultEntity.grade = @(ZERO);
            }
        }
        //判断
        if ([topicEntity.topicType isEqualToString:STUDYTOPICTYPE_TRUEORFALSE]) {
            for (CustomTOPassLevelTopicOptionEntity *entity in topicEntity.options) {
                if (entity.isSelected == YES) {
                    resultEntity.answer = entity.name;
                    if ([topicEntity.answer isEqualToString:entity.name]) {
                        resultEntity.grade = topicEntity.grade;
                        allScore += [topicEntity.grade integerValue];
                    }else {
                        resultEntity.grade = @(ZERO);
                    }
                }
            }
        }
        //单选
        if ([topicEntity.topicType isEqualToString:STUDYTOPICTYPE_SINGLE]) {
            for (CustomTOPassLevelTopicOptionEntity *entity in topicEntity.options) {
                if (entity.isSelected == YES) {
                    resultEntity.answer = entity.value;
                    if ([topicEntity.answer isEqualToString:entity.value]) {
                        resultEntity.grade = topicEntity.grade;
                        allScore += [topicEntity.grade integerValue];
                    }else {
                        resultEntity.grade = @(ZERO);
                    }
                }
            }
        }
        //填空、简答
        if ([topicEntity.topicType isEqualToString:PASSLEVELTOPICTYPE_GAPFILLING] || [topicEntity.topicType isEqualToString:PASSLEVELTOPICTYPE_SHORTANSWER]) {
                resultEntity.answer = topicEntity.answer;
                studyResult.passResult = [NSString stringWithFormat:@"%ld",Audit];//人工审核
        }
        [submitAnswerArray addObject:resultEntity];
    }
    studyResult.details = (NSArray<TOPassLevelResultDetailEntity>*)submitAnswerArray;
    studyResult.grade = [NSNumber numberWithFloat:allScore];
    if ([[self class] isBlankString:studyResult.passResult]) {
        studyResult.passResult = [NSString stringWithFormat:@"%ld",(self.emigrated.passGrade > allScore)?NotThrough:Through];
    }
    [XBLoadingView showHUDViewWithDefault];
    WS(weakSelf);
    [HTTP networkRequestWithURL:SERVERREQUESTURL(SUBMITEMIGRATEDANSWER) withRequestType:ZERO withParameter:studyResult withReturnValueBlock:^(id returnValue) {
        
        [XBLoadingView hideHUDViewWithDefault];
        if (RESULT(returnValue)) {
            [weakSelf determineIsQualified:[studyResult.grade integerValue] passResult:[studyResult.passResult integerValue]];
            if ([weakSelf.delegate respondsToSelector:@selector(emigratedFinish:)]) {
                [weakSelf.delegate emigratedFinish:studyResult.passResult];
            }
        }else{
            [XBLoadingView showHUDViewWithText:MESSAGE(returnValue)];
        }
        
    } withFailureBlock:^(NSError *error) {
        [XBLoadingView showHUDViewWithText:error.localizedDescription];
    }];
}

#pragma mark - 判断得分是否及格
- (void)determineIsQualified:(NSInteger)allScore passResult:(NSInteger)state
{
    BreakThroughFinishViewController *finish = [[[self class] getLearningCenterStoryboardClass] instantiateViewControllerWithIdentifier:@"BreakThroughFinishViewController"];
    finish.delegate = self;
    finish.preferredContentSize = CGSizeMake(520, 400);
    if (self.emigrated.passGrade > allScore && state != Audit) {
        finish.state = ZERO;
        finish.score = [NSString stringWithFormat:@"%ld",allScore];
        [self showPopoverView:finish];
        
    }else if (state == Audit) {
        finish.state = Audit;
        finish.score = [NSString stringWithFormat:@"%ld",allScore];
        [self showPopoverView:finish];
    }else {
        WS(weakSelf);
        [XBLoadingView showHUDViewWithDefault];
        NSString *url = [NSString stringWithFormat:SERVERREQUESTURL(GETINTEGRAL),RECRUITTHROUGH];
        [HTTP networkWithDictionaryRequestWithURL:url withRequestType:ONE withParameter:nil withReturnValueBlock:^(id returnValue) {
            [XBLoadingView hideHUDViewWithDefault];
            if (RESULT(returnValue)) {
                finish.state = ONE;
                finish.score = [NSString stringWithFormat:@"%ld",allScore];
                finish.integral = [NSString stringWithFormat:@"+%@",RESPONSE(returnValue)];
                [weakSelf showPopoverView:finish];
                
            }else {
                [XBLoadingView showHUDViewWithText:MESSAGE(returnValue)];
            }
            
        } withFailureBlock:^(NSError *error) {
            [XBLoadingView hideHUDViewWithDefault];
            [XBLoadingView showHUDViewWithText:error.localizedDescription];
        }];
    }
}

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

#pragma mark - 取消闯关
- (IBAction)exitButtonClickAction:(UIButton *)sender {
    
    WS(weakSelf);
    ShowAlertView(@"提示", @"是否退出闯关?", @[@"确认",@"取消"], UIAlertControllerStyleAlert, ^(NSInteger index) {
        if (index == ONE) {
            return;
        }
        if ([weakSelf.delegate respondsToSelector:@selector(dismissController:)]) {
            [weakSelf.delegate dismissController:YES];
        }
    });
}

#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