//
//  GTOQuestionManager.m
//  total
//
//  Created by freecui on 15/10/15.
//  Copyright (c) 2015年 free. All rights reserved.
//

#import "GTOQuestionManager.h"
#import "IBTImagePicker.h"

#import "GTOQuestion.h"
#import "ICRStoreResult.h"
#import "IBTAudioController.h"
#import "GTOStore.h"
#import <CoreLocation/CoreLocation.h>
#import <MapKit/MapKit.h>

#import "GTOPioneering.h"
#import "GTOLicence.h"
#import "GTOAnswerDetail.h"
#import "GTOAnswer.h"
#import "GTOQuestionBaseViewController.h"
#import "GTOQSingleSelectViewController.h"


#import "GTOQResultViewController.h"
@interface GTOQuestionManager () <CLLocationManagerDelegate>
@property (weak, nonatomic) UIViewController *m_baseRootViewCtrl;



@property (strong, nonatomic) NSDate *m_startTime;

@property (strong, nonatomic) CLLocationManager *m_locationManager;
@property (strong, nonatomic) NSString *m_nsLongtitude;
@property (strong, nonatomic) NSString *m_nsLatitude;

@property (strong, nonatomic) ICRStoreResult *m_result;

@property (copy, nonatomic) void(^openQuestAction)();




///
@property (strong, nonatomic) NSArray *d_arrQuestions;
@property (strong, nonatomic) NSArray *d_arrAnswers;
@property (strong, nonatomic) NSArray *d_arrQuestViewCtrls;
@end
@implementation GTOQuestionManager
+ (instancetype)sharedManager {
    
    static GTOQuestionManager *_sharedManager = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _sharedManager = [[[self class] alloc] init];
    });
    return _sharedManager;
}

#pragma mark - Getter
- (IBTImagePicker *)m_imagePicker {
    if (!_m_imagePicker) {
        self.m_imagePicker = [[IBTImagePicker alloc] init];
    }
    
    return _m_imagePicker;
}
#pragma mark - Setter
- (void)setM_bIsHelpViewAttachHide:(BOOL)bIsHelpViewAttachHide {
    _m_bIsHelpViewAttachHide = bIsHelpViewAttachHide;
    
    for (GTOQuestionBaseViewController *qVC in _d_arrQuestViewCtrls) {
        [qVC.c_helperView updateViewRect:bIsHelpViewAttachHide];
    }
}
- (void)setD_pioneering:(GTOPioneering *)d_pioneering {
//    if ([_d_pioneering isEqual:d_pioneering]) {
//        if (_openQuestAction) {
//            _openQuestAction();
//            self.openQuestAction = NULL;
//        }
//        return;
//    }
    
    
//    if (_openQuestAction) {
//        _openQuestAction();
//        self.openQuestAction = NULL;
//    }
    _d_pioneering = d_pioneering;
    
//    if (!_d_pioneering) {
//        [self cleanQuestions];
//        return;
//    }
    
    __block BOOL bIsQComplete = NO;
    __block BOOL bIsAComplete = NO;
    
    NSUInteger questionCount = [_d_pioneering.questions count];
    NSArray *arrQuestionsIDs = [_d_pioneering.questions valueForKeyPath:@"uuid"];
    
    ICRDatabaseFetchBlock fetchBlk = ^FMResultSet *(FMDatabase *db) {
//        NSString *sql = [NSString stringWithFormat:@"SELECT * FROM %@ WHERE %@ IN %@ ",//ORDER BY %@ ASC",
//                         [GTOQuestion TableName],@"uuid",[IBTModel ValuePlaceholdersWithCount:questionCount]];//,@"uuid"];
        NSString *sql = [NSString stringWithFormat:@"SELECT * FROM %@ WHERE %@ = ? ",//ORDER BY %@ ASC",
                         [GTOQuestion TableName],@"pioneeringUuid"];//,@"uuid"];
        CLog(@"%@",sql);
        return [db executeQuery:sql, _d_pioneering.uuid];
    };
    
    __weak typeof (self) weakSelf = self;
    ICRDatabaseFetchResultsBlock fetchResultBlk = ^(NSArray *fethcedObjects) {
        __strong __typeof(weakSelf)strongSelf = weakSelf;
        NSMutableArray *categoryQuestions = [NSMutableArray array];
        
        for(GTOQuestion *quesion in fethcedObjects) {
            if ([quesion.category isEqualToString:_d_category]) {
                [categoryQuestions addObject:quesion];
            }
        }
        strongSelf.d_arrQuestions = [NSArray arrayWithArray:categoryQuestions];
        bIsQComplete = YES;
        
//        if (_openQuestAction) {
//            _openQuestAction();
//            self.openQuestAction = NULL;
//        }
        if (bIsAComplete) {
            if (_openQuestAction) {
                _openQuestAction();
                self.openQuestAction = NULL;
            }
        }
    };
    
    ICRDataBaseController *dbCtrl = [ICRDataBaseController sharedController];
    [dbCtrl runFetchForClass:[GTOQuestion class]
                  fetchBlock:fetchBlk
           fetchResultsBlock:fetchResultBlk];
    
    
    //result
    ICRDatabaseFetchBlock srFetchBlk = ^FMResultSet *(FMDatabase *db) {
        __strong __typeof(weakSelf)strongSelf = weakSelf;
        NSString * sql = [NSString stringWithFormat:@"SELECT * FROM %@ WHERE %@=? and %@=? ORDER BY %@ ", [GTOAnswer TableName],  @"pioneeringUuid",@"category",@"questionUuid"];//,@"lineNo"];//根据油站找对应的答案
        return [db executeQuery:sql, strongSelf.d_pioneering.uuid,strongSelf.d_category,@"questionUuid"];
    };
    ICRDatabaseFetchResultsBlock srFetchResultsBlk = ^(NSArray *fetchedObjects) {
        __strong __typeof(weakSelf)strongSelf = weakSelf;
        //strongSelf.m_result = [fetchedObjects firstObject];
        strongSelf.d_arrAnswers = fetchedObjects;
        
        bIsAComplete = YES;
        if (bIsQComplete) {
            if (_openQuestAction) {
                _openQuestAction();
                strongSelf.openQuestAction = NULL;
            }
        }

    };
    
    [dbCtrl runFetchForClass:[GTOAnswer class]
                  fetchBlock:srFetchBlk
           fetchResultsBlock:srFetchResultsBlk];
}
- (void)setD_licence:(GTOLicence *)d_licence {
    //    if ([_d_pioneering isEqual:d_pioneering]) {
    //        if (_openQuestAction) {
    //            _openQuestAction();
    //            self.openQuestAction = NULL;
    //        }
    //        return;
    //    }
    
    
    //    if (_openQuestAction) {
    //        _openQuestAction();
    //        self.openQuestAction = NULL;
    //    }
    _d_licence = d_licence;
    
    //    if (!_d_pioneering) {
    //        [self cleanQuestions];
    //        return;
    //    }
    
    __block BOOL bIsQComplete = NO;
    __block BOOL bIsAComplete = NO;
    
    NSUInteger questionCount = [_d_licence.questions count];
    NSArray *arrQuestionsIDs = [_d_licence.questions valueForKeyPath:@"uuid"];
    
    ICRDatabaseFetchBlock fetchBlk = ^FMResultSet *(FMDatabase *db) {
//        NSString *sql = [NSString stringWithFormat:@"SELECT * FROM %@ WHERE %@ IN %@ ORDER BY %@ ASC",
//                         [GTOQuestion TableName],@"uuid",[IBTModel ValuePlaceholdersWithCount:questionCount],@"uuid"];
//        CLog(@"%@",sql);
//        return [db executeQuery:sql withArgumentsInArray:arrQuestionsIDs];
        NSString *sql = [NSString stringWithFormat:@"SELECT * FROM %@ WHERE %@ = ? ",//ORDER BY %@ ASC",
                         [GTOQuestion TableName],@"licenceUuid"];//,@"uuid"];
        CLog(@"%@",sql);
        return [db executeQuery:sql, _d_licence.uuid];
    };
    
    __weak typeof (self) weakSelf = self;
    ICRDatabaseFetchResultsBlock fetchResultBlk = ^(NSArray *fethcedObjects) {
        __strong __typeof(weakSelf)strongSelf = weakSelf;
        NSMutableArray *categoryQuestions = [NSMutableArray array];
        
        for(GTOQuestion *quesion in fethcedObjects) {
            if ([quesion.category isEqualToString:_d_category]) {
                [categoryQuestions addObject:quesion];
            }
        }
        strongSelf.d_arrQuestions = [NSArray arrayWithArray:categoryQuestions];
        bIsQComplete = YES;
        
        //        if (_openQuestAction) {
        //            _openQuestAction();
        //            self.openQuestAction = NULL;
        //        }
        if (bIsAComplete) {
            if (_openQuestAction) {
                _openQuestAction();
                self.openQuestAction = NULL;
            }
        }
    };
    
    ICRDataBaseController *dbCtrl = [ICRDataBaseController sharedController];
    [dbCtrl runFetchForClass:[GTOQuestion class]
                  fetchBlock:fetchBlk
           fetchResultsBlock:fetchResultBlk];
    
    
    //result
    ICRDatabaseFetchBlock srFetchBlk = ^FMResultSet *(FMDatabase *db) {
        __strong __typeof(weakSelf)strongSelf = weakSelf;
        NSString * sql = [NSString stringWithFormat:@"SELECT * FROM %@ WHERE %@=? and %@=? ORDER BY %@", [GTOAnswer TableName],  @"licenceUuid",@"category",@"questionUuid"];//,@"lineNo"];//根据油站找对应的答案
        return [db executeQuery:sql, strongSelf.d_licence.uuid,strongSelf.d_category];
    };
    ICRDatabaseFetchResultsBlock srFetchResultsBlk = ^(NSArray *fetchedObjects) {
        __strong __typeof(weakSelf)strongSelf = weakSelf;
        //strongSelf.m_result = [fetchedObjects firstObject];
        strongSelf.d_arrAnswers = fetchedObjects;
        
        bIsAComplete = YES;
        if (bIsQComplete) {
            if (_openQuestAction) {
                _openQuestAction();
                strongSelf.openQuestAction = NULL;
            }
        }
        
    };
    
    [dbCtrl runFetchForClass:[GTOAnswer class]
                  fetchBlock:srFetchBlk
           fetchResultsBlock:srFetchResultsBlk];
    
}
- (void)openQuestionVCFromViewControler:(UIViewController *)VC withPioneering:(GTOPioneering *)pioneering {
    if (![VC isKindOfClass:[UIViewController class] ] || !pioneering) {
        return;
    }

    self.m_baseRootViewCtrl = VC;
    __weak typeof (self)weakSelf = self;
    void(^block)(void) = ^(void) {
        __strong __typeof(weakSelf)strongSelf = weakSelf;
        NSMutableArray *arrViews = [NSMutableArray array];
        //NSUInteger questionsCount = _d_arrQuestions.count;//问题的总数
        NSUInteger questionIndex = 0;//uiIndex = 0;  每一个问题的标号
        NSUInteger answerIndex = 0;
        for(GTOQuestion *question in strongSelf.d_arrQuestions) {
            GTOAnswer *answer = [strongSelf.d_arrAnswers safeObjectAtIndex:questionIndex];
                GTOQuestionBaseViewController *questionVC = [[GTOQuestionBaseViewController alloc]initWithQuestion:question];
                questionVC.d_pioneering = _d_pioneering;
                questionVC.d_questionIndex = questionIndex;//uiIndex;
                questionVC.title = [NSString stringWithFormat:@"%@(%@/%@)",question.category,@(questionIndex + 1),@(_d_arrQuestions.count)];
                [arrViews addObject:questionVC];

            questionIndex ++;
            if (answer) answerIndex++;
            
        }
        
        for(GTOQuestionBaseViewController *questionBaseVC in arrViews){
            for(GTOAnswer *answer in _d_arrAnswers){
                if ([answer.questionUuid isEqualToString:questionBaseVC.d_question.uuid]) {
                    questionBaseVC.d_answer = answer;
                }
            }
        }
        //[allQuestionVCs count] > 0 ? arrViews :nil;
        strongSelf.d_arrQuestViewCtrls = [arrViews count] > 0 ? arrViews :nil;
        self.d_maxProblemLineno = answerIndex + 1;
        
        if (_d_arrQuestViewCtrls) {
            IBTUINavigationController *navCtrl = [[IBTUINavigationController alloc]initWithRootViewController:[arrViews firstObject]];
            NSArray *VCs = nil;
            if (answerIndex < [arrViews count])
            {
                VCs = [arrViews subarrayWithRange:NSMakeRange(0, answerIndex + 1)];

            }else {
//              TODO 结果页：答案显示
//                GTOQResultViewController *rVC = [[GTOQResultViewController alloc]initWithPioneering:_d_pioneering];
//                
//                NSMutableArray *mArr =  [NSMutableArray array];
//                [mArr addObjectsFromArray:arrViews];
//                [mArr addObject:rVC];
//                VCs = mArr;

                 VCs = [arrViews subarrayWithRange:NSMakeRange(0, answerIndex )];
            }
            
            navCtrl.viewControllers = VCs;
            self.d_vcs = [NSArray arrayWithArray:VCs];
            
            [VC presentViewController:navCtrl animated:YES completion:nil];
        }
        
    };
    
    self.openQuestAction = block;
    self.d_pioneering = pioneering;
    
}
- (void)openQuestionVCFromViewControler:(UIViewController *)VC
                                Licence:(GTOLicence *)licence
                             Pioneering: (GTOPioneering *)pioneering
                              IsNotEdit: (BOOL)isNotEdit
                           ProblemIndex: (NSInteger) problemIndex{
    BOOL isLicence = NO;  BOOL isPioneering = NO;
    if (licence) {
        isLicence = YES;
    }
    if (pioneering) {
        isPioneering = YES;
    }
    self.d_problemIndex = problemIndex;
    self.m_baseRootViewCtrl = VC;
    __weak typeof (self)weakSelf = self;
    void(^block)(void) = ^(void) {
        __strong __typeof(weakSelf)strongSelf = weakSelf;
        NSMutableArray *arrViews = [NSMutableArray array];
        //NSUInteger questionsCount = _d_arrQuestions.count;//问题的总数
        NSUInteger questionIndex = 0;//uiIndex = 0;  每一个问题的标号
        NSUInteger answerIndex = 0;
        for(GTOQuestion *question in strongSelf.d_arrQuestions) {
            GTOAnswer *answer = [strongSelf.d_arrAnswers safeObjectAtIndex:questionIndex];
            GTOQuestionBaseViewController *questionVC = [[GTOQuestionBaseViewController alloc]initWithQuestion:question];
            questionVC.d_notEdit = isNotEdit;
            questionVC.d_licence = _d_licence;
            questionVC.d_pioneering = _d_pioneering;
            questionVC.d_questionIndex = questionIndex;//uiIndex;
            questionVC.title = [NSString stringWithFormat:@"%@(%@/%@)",question.category,@(questionIndex + 1),@(_d_arrQuestions.count)];
            [arrViews addObject:questionVC];
            questionVC.testIndex=questionIndex;
            questionIndex ++;
            if (answer) answerIndex++;
            
        }
        
        for(GTOQuestionBaseViewController *questionBaseVC in arrViews){
            for(GTOAnswer *answer in _d_arrAnswers){
                if ([answer.questionUuid isEqualToString:questionBaseVC.d_question.uuid]) {
                    questionBaseVC.d_answer = answer;
                }
            }
        }
        //[allQuestionVCs count] > 0 ? arrViews :nil;
        strongSelf.d_arrQuestViewCtrls = [arrViews count] > 0 ? arrViews :nil;
        self.d_maxProblemLineno = answerIndex + 1;
        
        if (_d_arrQuestViewCtrls) {
            IBTUINavigationController *navCtrl = [[IBTUINavigationController alloc]initWithRootViewController:[arrViews firstObject]];
            NSArray *VCs = nil;
            BOOL condition = _d_problemIndex <= answerIndex && _d_problemIndex > 0;
            if (condition) {
                 VCs = [arrViews subarrayWithRange:NSMakeRange(0,_d_problemIndex)];
            }else {
                if (answerIndex < [arrViews count])
                {
                    VCs = [arrViews subarrayWithRange:NSMakeRange(0, answerIndex + 1)];
                    
                }else {
                    VCs = [arrViews subarrayWithRange:NSMakeRange(0,answerIndex )];
                }
            }
            
            navCtrl.viewControllers = VCs;
            self.d_vcs = [NSArray arrayWithArray:VCs];
            
            [VC presentViewController:navCtrl animated:YES completion:nil];
        }
        
    };
    
    self.openQuestAction = block;
    if (isPioneering) {
        //self.d_licence = nil;
        self.d_pioneering = pioneering;
    }
    if (isLicence) {
        //self.d_pioneering = nil;
        self.d_licence = licence;
    }
    
}
- (void)openQuestionVCFromViewControler:(UIViewController *)VC
                                Licence:(GTOLicence *)licence
                             Pioneering: (GTOPioneering *)pioneering;
{
//    [self openQuestionVCFromViewControler:VC
//                                  Licence:licence
//                               Pioneering:pioneering
//                                IsNotEdit:NO];
}
#pragma mark - Private Method
- (void)cleanQuestions {
    self.m_imagePicker = nil;
    self.d_arrQuestions = nil;
    self.d_arrAnswers = nil;
    self.d_arrQuestViewCtrls = nil;
    self.m_baseRootViewCtrl = nil;
    self.m_result = nil;
    self.m_store = nil;
}
- (UIViewController *)questionViewControlAtIndex:(NSUInteger)uiIndex {

        return uiIndex < [_d_arrQuestViewCtrls count] ? _d_arrQuestViewCtrls[uiIndex] : nil;

}
- (void)p_cleanQuestions {
    
}



























@end
