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

#import "AssessmentViewController.h"
#import "AssessmentHeaderView.h"
#import "AssessmentTableViewCell.h"
#import "AssessmentQualifiedViewController.h"
#import "AssessmentUnqualifiedViewController.h"


@interface AssessmentViewController ()<UITableViewDelegate,UITableViewDataSource,UnqualifiedDelegate,BackDelegate>

@property (nonatomic,strong) TOStudyTaskEntity *taskDetails;

/**
 三次重考机会
 */
@property (nonatomic,assign) NSInteger retakeCount;
@property (strong, nonatomic) TOStudyResultEntity *studyResult;

@end

@implementation AssessmentViewController


#pragma mark -渲染完成
- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    self.navigationController.fd_fullscreenPopGestureRecognizer.enabled = NO;
    if ([self.navigationController respondsToSelector:@selector(interactivePopGestureRecognizer)]) {
        self.navigationController.interactivePopGestureRecognizer.enabled = NO;
    }
}

#pragma mark -视图即将消失
- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    self.navigationController.fd_fullscreenPopGestureRecognizer.enabled = YES;
    if ([self.navigationController respondsToSelector:@selector(interactivePopGestureRecognizer)]) {
        self.navigationController.interactivePopGestureRecognizer.enabled = YES;
    }
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.retakeCount = 3;
    [self getExaminationQuestions];
    [self httpGetAnswerId];
}

#pragma mark - 获取考题
- (void)getExaminationQuestions
{
    WS(weakSelf);
    [XBLoadingView showHUDViewWithDefault];;
    [HTTP networkWithDictionaryRequestWithURL:[NSString stringWithFormat:SERVERREQUESTURL(STUDYITEMDETAIL),self.taskId] withRequestType:ONE withParameter:nil withReturnValueBlock:^(id returnValue) {
        
        [XBLoadingView hideHUDViewWithDefault];
        if (RESULT(returnValue)) {
            weakSelf.taskDetails = [[TOStudyTaskEntity alloc]initWithDictionary:RESPONSE(returnValue) error:nil];
            [weakSelf assessmentCountdown];
            [weakSelf.assessmentTableView reloadData];
        }else {
            [XBLoadingView showHUDViewWithText:MESSAGE(returnValue)];
        }
        
    }withFailureBlock:^(NSError *error) {
        [XBLoadingView showHUDViewWithText:error.localizedDescription];
    }];
}

#pragma mark - 考核计时
- (void)assessmentCountdown
{
    self.assessmentTitleLabel.text = self.taskDetails.title;
    [self.assessmentTimeLabel beginCountDownWithTimeInterval:self.taskDetails.examMinute*60];
    WS(weakSelf);
    //倒计时结束
    [self.assessmentTimeLabel setCountDownCompleteBlock:^{
        [weakSelf submitAnswer];
    }];
}

#pragma mark - <UITableViewDelegate,UITableViewDataSource>
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    AssessmentTableViewCell *assessmentCell = [tableView dequeueReusableCellWithIdentifier:@"AssessmentTableViewCell" forIndexPath:indexPath];
    TOStudyTopicEntity *entity = self.taskDetails.topics[indexPath.section];
    assessmentCell.studyEntity = entity.options[indexPath.row];
    return assessmentCell;
}

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

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    CustomTOStudyTopicEntity *entity = self.taskDetails.topics[indexPath.section];
    CustomTOStudyTopicOptionEntity *answer = entity.options[indexPath.row];
    return answer.answerHeight;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return self.taskDetails.topics.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    TOStudyTopicEntity *entity = self.taskDetails.topics[section];
    return entity.options.count;
}

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

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    TOStudyTopicEntity *entitys = self.taskDetails.topics[indexPath.section];
    if ([entitys.topicType isEqualToString:STUDYTOPICTYPE_SINGLE] || [entitys.topicType isEqualToString:STUDYTOPICTYPE_TRUEORFALSE]) {
        for (int i=0; i<entitys.options.count; i++) {
            CustomTOStudyTopicOptionEntity *entity = entitys.options[i];
            if (i == indexPath.row) {
                entity.isSelected = !entity.isSelected;
            }else {
                entity.isSelected = NO;
            }
        }
    }else if ([entitys.topicType isEqualToString:STUDYTOPICTYPE_MULTIPLE]) {
        CustomTOStudyTopicOptionEntity *answer = entitys.options[indexPath.row];
        answer.isSelected = !answer.isSelected;
    }
    [self.assessmentTableView reloadSections:[NSIndexSet indexSetWithIndex:indexPath.section] withRowAnimation:UITableViewRowAnimationNone];
}

#pragma mark - 提交
- (IBAction)submitButtonClickAction:(UIButton *)sender {
    
    [self.assessmentTimeLabel stopTimer];
    [self submitAnswer];
}

#pragma mark - 提交考核结果
- (void)submitAnswer
{
    TOStudyResultEntity *studyResult = self.studyResult;
//    studyResult.taskId = self.taskId;
//    studyResult.employeeId = [Shoppersmanager manager].shoppers.employee.fid;
    studyResult.submitTime = [[NSDate date] httpParameterString];
    NSArray *answerArray = self.taskDetails.topics;
    NSMutableArray *submitAnswerArray = [NSMutableArray array];
    NSInteger allScore = 0;//总分
    for (TOStudyTopicEntity *topicEntity in answerArray) {
        
        TOStudyResultDetailEntity *resultEntity = [[TOStudyResultDetailEntity alloc] init];
        resultEntity.topicId = topicEntity.fid;
        //多选
        if ([topicEntity.topicType isEqualToString:STUDYTOPICTYPE_MULTIPLE]) {
            NSMutableString *answers = [[NSMutableString alloc] init];
            for (CustomTOStudyTopicOptionEntity *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 (CustomTOStudyTopicOptionEntity *entity in topicEntity.options) {
                if (entity.isSelected == YES) {
                    resultEntity.answer = entity.name;
                    if ([topicEntity.answer isEqualToString:entity.name]) {
                        allScore += [topicEntity.grade integerValue];
                        resultEntity.grade = topicEntity.grade;
                    }else {
                        resultEntity.grade = @(ZERO);;
                    }
                }
            }
        }
        //单选
        if ([topicEntity.topicType isEqualToString:STUDYTOPICTYPE_SINGLE]) {
            for (CustomTOStudyTopicOptionEntity *entity in topicEntity.options) {
                if (entity.isSelected == YES) {
                    resultEntity.answer = entity.value;
                    if ([topicEntity.answer isEqualToString:entity.value]) {
                        allScore += [topicEntity.grade integerValue];
                        resultEntity.grade = topicEntity.grade;
                    }else {
                        resultEntity.grade = @(ZERO);;
                    }
                }
            }
        }
        [submitAnswerArray addObject:resultEntity];
    }
    studyResult.details = (NSArray<TOStudyResultDetailEntity>*)submitAnswerArray;
    studyResult.grade = [NSNumber numberWithInteger:allScore];
    //判断考核是否合格
    studyResult.examResult = (self.taskDetails.passGrade <= allScore)?@"1":@"0";
    [XBLoadingView showHUDViewWithDefault];
    WS(weakSelf);
    NSLog(@"%@",[[studyResult toDictionary] JSONString]);
    [HTTP networkRequestWithURL:SERVERREQUESTURL(SUBMITANSWER) withRequestType:ZERO withParameter:studyResult withReturnValueBlock:^(id returnValue) {
        
        [XBLoadingView hideHUDViewWithDefault];
        if (RESULT(returnValue)) {
            [weakSelf determineIsQualified:[studyResult.grade integerValue]];
        }else{
            [XBLoadingView showHUDViewWithText:MESSAGE(returnValue)];
        }
        
    } withFailureBlock:^(NSError *error) {
        [XBLoadingView showHUDViewWithText:error.localizedDescription];
    }];
}

- (void)httpGetAnswerId {
    WS(weakSelf);
    NSString *url = [NSString stringWithFormat:@"/study/startExam/%@/%@", self.taskId, [Shoppersmanager manager].shoppers.employee.fid];
    [HTTP networkRequestWithURL:SERVERREQUESTURL(url) withRequestType:(GET) withParameter:nil withReturnValueBlock:^(id returnValue) {
        NSLog(@"%@", returnValue);
        weakSelf.studyResult = [[TOStudyResultEntity alloc] initWithDictionary:RESPONSE(returnValue) error:nil];
    } withFailureBlock:^(NSError *error) {
        
    }];
}


#pragma mark - 判断得分是否及格
- (void)determineIsQualified:(NSInteger)allScore
{
    if (self.taskDetails.passGrade > allScore) {
        AssessmentUnqualifiedViewController *unQualified = [[[self class] getLearningCenterStoryboardClass] instantiateViewControllerWithIdentifier:@"AssessmentUnqualifiedViewController"];
        unQualified.allScore = [NSString stringWithFormat:@"%ld",allScore];
        unQualified.opportunityCount = self.retakeCount;
        unQualified.delgate = self;
        unQualified.preferredContentSize = CGSizeMake(300, 300);
        unQualified.modalPresentationStyle = UIModalPresentationFormSheet;
        UIPopoverPresentationController *pop = unQualified.popoverPresentationController;
        pop.sourceView = unQualified.view;
        [self presentViewController:unQualified animated:YES completion:nil];
    
    }else {
        WS(weakSelf);
        [XBLoadingView showHUDViewWithDefault];
        [HTTP networkWithDictionaryRequestWithURL:[NSString stringWithFormat:SERVERREQUESTURL(GETINTEGRAL),INSPECTIONTHROUGH] withRequestType:ONE withParameter:nil withReturnValueBlock:^(id returnValue) {
            [XBLoadingView hideHUDViewWithDefault];
            if (RESULT(returnValue)) {
                AssessmentQualifiedViewController *qualified = [[[weakSelf class] getLearningCenterStoryboardClass] instantiateViewControllerWithIdentifier:@"AssessmentQualifiedViewController"];
                qualified.delegate = self;
                qualified.intrgral = [NSString stringWithFormat:@"+%@",RESPONSE(returnValue)];
                qualified.allScore = [NSString stringWithFormat:@"%ld",allScore];
                qualified.preferredContentSize = CGSizeMake(300, 300);
                qualified.modalPresentationStyle = UIModalPresentationFormSheet;
                UIPopoverPresentationController *pop = qualified.popoverPresentationController;
                pop.sourceView = qualified.view;
                [weakSelf presentViewController:qualified animated:YES completion:nil];
            }else {
                [XBLoadingView showHUDViewWithText:MESSAGE(returnValue)];
            }
            
        } withFailureBlock:^(NSError *error) {
            [XBLoadingView hideHUDViewWithDefault];
            [XBLoadingView showHUDViewWithText:error.localizedDescription];
        }];
    }
}

#pragma mark - <UnqualifiedDelegate>考核不通过
#pragma mark - 重新开始
- (void)startAgainAction
{
    WS(weakSelf);
    self.retakeCount -= ONE;
    [self.assessmentTimeLabel stopTimer];
    [self dismissViewControllerAnimated:YES completion:^{
        [weakSelf.assessmentTableView setContentOffset:CGPointMake(0,0) animated:YES];
        [weakSelf getExaminationQuestions];
    }];
}

#pragma mark - 再学一遍
- (void)learnAgainAction
{
    WS(weakSelf);
    [self.assessmentTimeLabel stopTimer];
    [self dismissViewControllerAnimated:YES completion:^{
        [weakSelf.navigationController popViewControllerAnimated:YES];
        if ([weakSelf.delegate respondsToSelector:@selector(learningAgainButtonClick:)]) {
            [weakSelf.delegate learningAgainButtonClick:weakSelf.indexPath];
        }
    }];
}

#pragma mark - <BackDelegate>返回
- (void)backClickAction
{
    WS(weakSelf);
    [self dismissViewControllerAnimated:YES completion:^{
        [weakSelf.navigationController popViewControllerAnimated:YES];
        if ([weakSelf.delegate respondsToSelector:@selector(inspectionThroughAction:)]) {
            [weakSelf.delegate inspectionThroughAction:weakSelf.indexPath];
        }
    }];
}









@end
