//
//  PatrolExamViewModel.m
//  patrol
//
//  Created by Javen on 2017/3/3.
//  Copyright © 2017年 上海勾芒科技有限公司. All rights reserved.
//

#import "PatrolExamViewModel.h"
static UILabel *stringLabel = nil;

@interface PatrolExamViewModel ()
@property (strong, nonatomic) NSCache *cellCache;
@property (strong, nonatomic) NSMutableArray *arrDefautCellModel;



@end
@implementation PatrolExamViewModel

- (void)configData:(NSDictionary *)data {
    ZJPatrolDetail *detail = [ZJPatrolDetail modelWithDic:data];
    self.detail = detail;
    if (detail.inspectors.count > 0) {
        self.inspector = detail.inspectors[0];
    }
    if (detail.results.count > 0) {
        self.result = detail.results[0];
    }
    ZJPatrolDetail_inspectors *inspect = detail.inspectors.firstObject;
    if (self.state != [PatrolExamState stateWithCode:inspect.state]) {
//        [kNotification postNotificationName:UPDATEPATROLONLINELIST object:nil];
        self.state = [PatrolExamState stateWithCode:inspect.state];
    }
    //1.先获取所有的类型
    NSMutableSet *set = [[NSMutableSet alloc] init];
    for (ZJPatrolDetail_questions *questins in detail.questions) {
        [set addObject:questins.category];
    }
    //2.排序分类
    NSArray *sortDesc = @[ [[NSSortDescriptor alloc] initWithKey:nil ascending:YES] ];
    NSArray *sortSetArray = [set sortedArrayUsingDescriptors:sortDesc];

    //3.遍历类型分组问题
    self.arrCellData = [NSMutableArray array];

    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{ //生成一个用于计算文本高度的label
        stringLabel = [[UILabel alloc] init];
        stringLabel.font = [UIFont systemFontOfSize:17];
        stringLabel.numberOfLines = 0;
    });
    for (NSString *category in sortSetArray) {
        for (NSString *string in self.airplanModes) {
            if ([category rangeOfString:string].location != NSNotFound) {
                [self.airplanModeArray addObject:category];
            }
        }
        PatrolExamCellViewModel *cateModel = [PatrolExamCellViewModel modelWithType:ExamCellTypeCatogory viewModel:self];
        cateModel.category = category;
        stringLabel.text = category;
        cateModel.level = 0;
        cateModel.height = [stringLabel sizeThatFits:CGSizeMake(ScreenSize.width - 32, MAXFLOAT)].height + 10;
        [self.arrCellData addObject:cateModel];
        for (ZJPatrolDetail_questions *questions in detail.questions) {
            //判断是否已答题
            if (detail.results.count > 0) {
                ZJPatrolDetail_results *result = detail.results[0];
                for (ZJPatrolDetail_results_answers *answer in result.answers) {
                    if ([answer.questionUuid isEqualToString:questions.uuid]) {
                        //把答案根据问题id存放
                        [self.dicAnswers setObject:answer forKey:answer.questionUuid];
                    }
                }
            }else if (kUser.configModel.automaticAnswer) {
                //判断是否有自动答题权限
                //  - ExamCellTypeSingle: 单选题
                //  - ExamCellTypeMultiple: 多选题
                //  - ExamCellTypeYesNO: 是非题
                NSInteger questionType = [questions.type integerValue];
                if (questionType == ExamCellTypeSingle || questionType == ExamCellTypeMultiple || questionType == ExamCellTypeYesNO) {
                    ZJPatrolDetail_results_answers *answer = [[ZJPatrolDetail_results_answers alloc] init];
                    answer.questionUuid = questions.uuid;
                    NSArray *standAnswer = [questions.standAnswer componentsSeparatedByString:@","];
                    NSMutableArray *standAnswerAttay = [NSMutableArray array];
                    for (NSString *standAnswerString in standAnswer) {
                        ZJPatrolDetail_results_answers_details *detail = [[ZJPatrolDetail_results_answers_details alloc] init];
                        detail.index = [NSNumber numberWithInteger:[standAnswerString integerValue]];
                        [standAnswerAttay addObject:detail];
                    }
                    answer.details = (NSMutableArray<ZJPatrolDetail_results_answers_details> *)standAnswerAttay;
                    [self.dicAnswers setObject:answer forKey:answer.questionUuid];
                }
            }
        }
        //获取问题题目
        for (ZJPatrolDetail_questions *questions in detail.questions) {
            //如果等于临时
            if (detail.temp) {
                if ([questions.photoType isEqualToString:@"no"]) {
                    questions.photoType = @"all";
                }
            }
            if ([questions.category isEqualToString:category]) {
            
                //问题题目
                PatrolExamCellViewModel *titleModel = [PatrolExamCellViewModel modelWithType:ExamCellTypeQuestion viewModel:self];
                titleModel.question = questions;
                NSString *title = nil;
                if (questions.titleNumber) {
                    title = [NSString stringWithFormat:@"%@ %@",questions.titleNumber,questions.title];
                }else {
                    title = questions.title;
                }
                stringLabel.text = title;
                titleModel.height = [stringLabel sizeThatFits:CGSizeMake(ScreenSize.width - 110, MAXFLOAT)].height + 28;
                titleModel.level = 1;
                [self.arrCellData addObject:titleModel];
                //获取问题选项
                NSMutableArray *arrQuestionDetails = [self configWithQuestons:questions];
                [self.arrCellData addObjectsFromArray:arrQuestionDetails];

                //添加附件栏
                PatrolExamCellViewModel *attModel = [PatrolExamCellViewModel modelWithType:ExamCellTypeAttachment viewModel:self];
                attModel.question = questions;
                attModel.height = 55;
                attModel.level = 2;
                [self.arrCellData addObject:attModel];
            }
        }
    }
}

/**
 把问题下的选项处理成cellModel

 @param questions 问题model
 @return 处理之后的数据
 */
- (NSMutableArray *)configWithQuestons:(ZJPatrolDetail_questions *)questions {
    NSMutableArray *arrQuestionDetails = [NSMutableArray array];

//    获取问题对应的答案
//    ZJPatrolDetail_results_answers *answer = [self.dicAnswers objectForKey:questions.uuid];

    //获取任务类型
    NSInteger type = [questions.type integerValue];
    //单选/多选/单选打分
    if (type == ExamCellTypeSingle ||
        type == ExamCellTypeMultiple ||
        type == ExamCellTypeSelectScore) {

        //获取问题下的选项
        for (ZJPatrolDetail_questions_details *detail in questions.details) {

            PatrolExamCellViewModel *questionDetail = [PatrolExamCellViewModel modelWithType:type viewModel:self];
            questionDetail.question = questions;
            questionDetail.questionDetail = detail;
            //            questionDetail.answer = answer;

            //计算文本高度
            stringLabel.text = detail.value;
            questionDetail.height = [stringLabel sizeThatFits:CGSizeMake(ScreenSize.width - 100, MAXFLOAT)].height + 17;

            questionDetail.level = 2;
            [arrQuestionDetails addObject:questionDetail];
        }
    } else {
        PatrolExamCellViewModel *questionDetail = [PatrolExamCellViewModel modelWithType:type viewModel:self];
        questionDetail.question = questions;
        //        questionDetail.answer = answer;
        if (type == ExamCellTypeInput || type == ExamCellTypeScore) {
            questionDetail.height = 120;
        } else {
            questionDetail.height = 54;
        }
        questionDetail.level = 2;
        [arrQuestionDetails addObject:questionDetail];
    }
    return arrQuestionDetails;
}

- (NSMutableArray *)indexPathWithSelectIndexPath:(NSIndexPath *)indexPath {
    PatrolExamCellViewModel *cellModel = [self.arrCellData yx_objectAtIndex:indexPath.row];
    if (cellModel.isOpen) {
        NSMutableArray *arrIndexPath = [NSMutableArray array];
        NSInteger count = self.arrCellData.count;
        NSMutableArray *dataCopy = self.arrCellData.mutableCopy;
        NSMutableArray *arrCache = [self lazyLoadCacheWithCellModel:cellModel];
//        cellModel.isOpen = NO;
        for (NSInteger i = indexPath.row + 1; i < count; i++) {
            PatrolExamCellViewModel *nextModel = self.arrCellData[i];
            if (nextModel.level > cellModel.level) {
                [dataCopy removeObject:nextModel];
                NSIndexPath *index = [NSIndexPath indexPathForRow:i inSection:0];
                [arrIndexPath addObject:index];
                
                [arrCache addObject:nextModel];
            } else {
                break;
            }
        }

        self.arrCellData = dataCopy;
        return arrIndexPath;
    } else {
        NSMutableArray *arrCache = [self.cellCache objectForKey:cellModel];
        NSRange range = NSMakeRange(indexPath.row + 1, arrCache.count);
        NSIndexSet *indexSet = [NSIndexSet indexSetWithIndexesInRange:range];
        [self.arrCellData insertObjects:arrCache atIndexes:indexSet];
//        cellModel.isOpen = YES;
        NSMutableArray *indexPaths = [NSMutableArray array];
        for (NSInteger i = 0; i < arrCache.count; i++) {
            NSIndexPath *index = [NSIndexPath indexPathForRow:indexPath.row + i + 1 inSection:0];
            [indexPaths addObject:index];
        }
        [arrCache removeAllObjects];
        return indexPaths;
    }
}

- (NSMutableArray *)indexPathsWithSelectIndexPath:(NSIndexPath *)indexPath {
    PatrolExamCellViewModel *cellModel = [self.arrCellData yx_objectAtIndex:indexPath.row];
    if (cellModel.isOpen) {
        NSMutableArray *arrIndexPath = [NSMutableArray array];
        NSInteger count = self.arrCellData.count;
        NSMutableArray *arrCache = [self lazyLoadCacheWithCellModel:cellModel];
        cellModel.isOpen = NO;
        for (NSInteger i = indexPath.row + 1; i < count; i++) {
            PatrolExamCellViewModel *nextModel = self.arrCellData[i];
            if (nextModel.level > cellModel.level) {
//                [dataCopy removeObject:nextModel];
                NSIndexPath *index = [NSIndexPath indexPathForRow:i inSection:0];
                [arrIndexPath addObject:index];
                
                [arrCache addObject:nextModel];
            } else {
                break;
            }
        }
        
//        self.arrCellData = dataCopy;
        return arrIndexPath;
    } else {
        NSMutableArray *arrCache = [self.cellCache objectForKey:cellModel];
//        NSRange range = NSMakeRange(indexPath.row + 1, arrCache.count);
//        NSIndexSet *indexSet = [NSIndexSet indexSetWithIndexesInRange:range];
//        [self.arrCellData insertObjects:arrCache atIndexes:indexSet];
        cellModel.isOpen = YES;
        NSMutableArray *indexPaths = [NSMutableArray array];
        for (NSInteger i = 0; i < arrCache.count; i++) {
            NSIndexPath *index = [NSIndexPath indexPathForRow:indexPath.row + i + 1 inSection:0];
            [indexPaths addObject:index];
        }
//        [arrCache removeAllObjects];
        return indexPaths;
    }
}


- (NSMutableArray *)openIndexPaths:(NSIndexPath *)indexPath {
    PatrolExamCellViewModel *cellModel = [self.arrCellData yx_objectAtIndex:indexPath.row];
    NSMutableArray *arrCache = [self.cellCache objectForKey:cellModel];
    //        NSRange range = NSMakeRange(indexPath.row + 1, arrCache.count);
    //        NSIndexSet *indexSet = [NSIndexSet indexSetWithIndexesInRange:range];
    //        [self.arrCellData insertObjects:arrCache atIndexes:indexSet];
    cellModel.isOpen = YES;
    NSMutableArray *indexPaths = [NSMutableArray array];
    for (NSInteger i = 0; i < arrCache.count; i++) {
        NSIndexPath *index = [NSIndexPath indexPathForRow:indexPath.row + i + 1 inSection:0];
        [indexPaths addObject:index];
    }
    //        [arrCache removeAllObjects];
    return indexPaths;
}

- (NSMutableArray *)closeIndexPaths:(NSIndexPath *)indexPath {
    PatrolExamCellViewModel *cellModel = [self.arrCellData yx_objectAtIndex:indexPath.row];
    NSMutableArray *arrIndexPath = [NSMutableArray array];
    NSInteger count = self.arrCellData.count;
    NSMutableArray *arrCache = [self lazyLoadCacheWithCellModel:cellModel];
    cellModel.isOpen = NO;
    for (NSInteger i = indexPath.row + 1; i < count; i++) {
        PatrolExamCellViewModel *nextModel = self.arrCellData[i];
        if (nextModel.level > cellModel.level) {
            //                [dataCopy removeObject:nextModel];
            NSIndexPath *index = [NSIndexPath indexPathForRow:i inSection:0];
            [arrIndexPath addObject:index];
            
            [arrCache addObject:nextModel];
        } else {
            break;
        }
    }
    
    //        self.arrCellData = dataCopy;
    return arrIndexPath;
}

//- (NSMutableArray *)

- (NSMutableArray *)lazyLoadCacheWithCellModel:(PatrolExamCellViewModel *)cellModel {
    //初始化问题的缓存
    if (![self.cellCache objectForKey:cellModel]) {
        NSMutableArray *arrCache = [NSMutableArray array];
        [self.cellCache setObject:arrCache forKey:cellModel];
    }
    NSMutableArray *arrCache = [self.cellCache objectForKey:cellModel];
    return arrCache;
}

/**
 打开所有题目
 */
- (NSMutableArray *)openAll {
    
    NSMutableArray *arr = [NSMutableArray array];
//    for (NSInteger i = 0; i < self.arrCellData.count; i++) {
//        PatrolExamCellViewModel *cellVM = self.arrCellData[i];
//        if (cellVM.level == 0) {
//            NSIndexPath *indexPath = [NSIndexPath indexPathForRow:i inSection:0];
//            [arr addObjectsFromArray:[self indexPathsWithSelectIndexPath:indexPath]];
//        }
//    }
//    
//    
//    self.arrCellData = self.arrDefautCellModel.mutableCopy;
    
    
    for (PatrolExamCellViewModel *model in self.arrDefautCellModel) {
        if (model.level == 0) {
            
            model.isOpen = YES;
        }
    }
    self.arrCellData = self.arrDefautCellModel.mutableCopy;
    [self.cellCache removeAllObjects];

    if (self.blockReloadData) {
        self.blockReloadData();
    }
    
    return arr;
}

/**
 折叠所有题目
 */
- (NSMutableArray *)closeAll {
    NSMutableArray *arrTempCellModel = self.arrCellData.mutableCopy;

    for (PatrolExamCellViewModel *model in self.arrDefautCellModel) {
//        model.isOpen = NO;
        if (model.level > 0) {
            [arrTempCellModel removeObject:model];
        }
    }
    
    NSMutableArray *arr = [NSMutableArray array];
    for (NSInteger i = 0; i < self.arrCellData.count; i++) {
        PatrolExamCellViewModel *cellVM = self.arrCellData[i];
        if (cellVM.level == 0) {
            NSIndexPath *indexPath = [NSIndexPath indexPathForRow:i inSection:0];
            [arr addObjectsFromArray:[self closeIndexPaths:indexPath]];
        }
    }
    
    self.arrCellData = arrTempCellModel;

//    if (self.blockReloadData) {
//        self.blockReloadData();
//    }
    return arr;
}

- (ZJPatrolDetail_results_answers *)answerFromCellModel:(PatrolExamCellViewModel *)cellModel {
    ZJPatrolDetail_results_answers *answer = cellModel.answer;
    if (!answer) {
        //创建答案对象
        ZJPatrolDetail_results_answers *newAnswer = [ZJPatrolDetail_results_answers new];
        newAnswer.questionUuid = cellModel.question.uuid;
        newAnswer.details = (NSMutableArray<ZJPatrolDetail_results_answers_details> *) [NSMutableArray array];
        [self.dicAnswers setObject:newAnswer forKey:cellModel.question.uuid];
    }
    cellModel.answer = cellModel.answer;
    return cellModel.answer;
}

#pragma mark - http
- (void)httpDetailComplete:(void (^)(void))complete {
    [RequestManager request_PatrolPlanDetail:self.plan.uuid storeUuid:self.storeResult.store_uuid success:^(id returnValue) {
        if ([BaseViewModel verifyData:returnValue]) {
            NSArray *arrRecord = returnValue[@"data"][@"records"];
            if (![arrRecord isKindOfClass:[NSArray class]] && arrRecord.count == 0) {
                return;
            }
            [self configData:arrRecord[0]];
            if (complete) {
                complete();
            }
        }else {
            [IBTLoadingView hideHUDWithText:nil];
        }
        self.arrDefautCellModel = self.arrCellData.mutableCopy;
    } failure:^(id errorValue) {
        [IBTLoadingView hideHUDWithText:nil];
        [IBTLoadingView showTextOnly:errorValue];
    }];
}

- (void)httpSubmitAnswerWithAction:(AnswerSubmitAction)action complete:(void (^)(BOOL isSuccess))complete {
    if (!self.result) {
        return;
    }
    NSString *type = nil;
    if (action == AnswerSubmitActionSave) {
        type = @"save";
    } else {
        type = @"commit";
    }
    NSArray *arrKeys = self.dicAnswers.allKeys;
    NSMutableArray *arrAnswer = [NSMutableArray array];
    for (NSString *key in arrKeys) {
        ZJPatrolDetail_results_answers *answer = [self.dicAnswers objectForKey:key];
        NSDictionary *dic = answer.toDictionary;
        [arrAnswer addObject:dic];
    }
    //如果答案为空，无法提交
    if (!arrAnswer.count) {
        complete(YES);
        return;
    }
    NSDictionary *param = @{ @"uuid" : self.result.uuid,
                             @"answers" : arrAnswer };
    [RequestManager request_SubmitPatrolPlan:self.plan.uuid type:type parameter:param success:^(id returnValue) {
        if ([BaseViewModel verifyData:returnValue]) {
            complete(YES);
        }else {
            complete(NO);
        }
    } failure:^(id errorValue) {
        [IBTLoadingView hideHUDWithText:nil];
        [IBTLoadingView showTextOnly:errorValue];
    }];
}

- (void)setStoreResult:(Results *)storeResult {
    _storeResult = storeResult;
    self.state = [PatrolExamState stateWithCode:storeResult.state];
}

- (void)setPlan:(PatrolTaskCustomModel *)plan {
    _plan = plan;
    NSString *date = [[NSDate date] yearMonthDayString];
    if ([[self class] compareTime:date date2:plan.beginDate] == -1 && [[self class] compareTime:date date2:plan.endDate] == 1) {
        self.state.type = PatrolExamStateOutOfDate;
    }
}

/**
 比较时间字符串大小
 
 @param date1 时间1
 @param date2 时间2
 
 */
// -1 a<b  0 a==b  1 a>b
+ (NSInteger)compareTime:(NSString *)date1 date2:(NSString *)date2
{
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd"];
    NSDate *newDate1 = [dateFormatter dateFromString:date1];
    NSDate *newDate2 = [dateFormatter dateFromString:date2];
    return [newDate1 compare:newDate2];
}

- (NSCache *)cellCache {
    if (!_cellCache) {
        _cellCache = [[ NSCache alloc] init];
    }
    return _cellCache;
}

- (NSMutableDictionary *)dicAnswers {
    if (!_dicAnswers) {
        _dicAnswers = [NSMutableDictionary dictionary];
    }
    return _dicAnswers;
}

- (NSArray *)airplanModes {
    if (!_airplanModes) {
        _airplanModes = @[@"油罐区",@"加油区",@"卸油区"];
    }
    return _airplanModes;
}

- (NSMutableArray *)airplanModeArray {
    if (!_airplanModeArray) {
        _airplanModeArray = [NSMutableArray array];
    }
    return _airplanModeArray;
}

@end
