//
//  ICRQuestionManager.m
//  XFFruit
//
//  Created by Xummer on 15/6/2.
//  Copyright (c) 2015年 Xummer. All rights reserved.
//

#import "ICRQuestionManager.h"
#import "IBTImagePicker.h"
#import "ICRPatrolPlan.h"
#import "ICRQuestion.h"
#import "ICRStoreResult.h"
#import "IBTAudioController.h"

#import "ICRQuestionBaseViewController.h"
#import "ICRQResultViewController.h"

#import <CoreLocation/CoreLocation.h>
#import <MapKit/MapKit.h>

@interface ICRQuestionManager () <CLLocationManagerDelegate>
@property (weak, nonatomic) UIViewController *m_baseRootViewCtrl;
@property (strong, nonatomic) NSArray *m_arrQuestions;
@property (strong, nonatomic) NSArray *m_arrAnswers;
@property (strong, nonatomic) NSArray *m_arrQuestViewCtrls;
@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)();

@end

@implementation ICRQuestionManager

#pragma mark - Class Method
+ (instancetype)sharedManager {
    static ICRQuestionManager *_sharedManager = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _sharedManager = [[[self class] alloc] init];
    });
    
    return _sharedManager;
}

#pragma mark - Life Cycle
- (instancetype)init {
    self = [super init];
    if (!self) {
        return nil;
    }
    
    [[IBTAudioController sharedController] setup];
    [self initLocaltionMgr];
    
    return self;
}

#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 (ICRQuestionBaseViewController *qVC in _m_arrQuestViewCtrls) {
        [qVC.m_helperView updateViewRect:bIsHelpViewAttachHide];
    }
}

- (void)setM_patrolPlan:(ICRPatrolPlan *)patrolPlan {
    if ([_m_patrolPlan isEqual:patrolPlan]) {
        if (_openQuestAction) {
            _openQuestAction();
            self.openQuestAction = NULL;
        }
        return;
    }
    
    _m_patrolPlan = patrolPlan;
    
    if (!_m_patrolPlan) {
        [self cleanQuestions];
        return;
    }
    
    __block BOOL bIsQComplete = NO;
    __block BOOL bIsAComplete = NO;
    
    NSUInteger uiQuestionsCount = [_m_patrolPlan.questions count];
    
    NSArray *arrQuestIDs = [_m_patrolPlan.questions valueForKeyPath:@"uuid"];
    
    ICRDatabaseFetchBlock fetchBlk = ^FMResultSet *(FMDatabase *db) {
        NSString * sql = [NSString stringWithFormat:@"SELECT * FROM %@ WHERE %@ IN %@ ORDER BY %@ ASC", [ICRQuestion TableName], @"uuid", [IBTModel ValuePlaceholdersWithCount:uiQuestionsCount], @"lineNo"];
        NSLog(@"%@",sql);
        return [db executeQuery:sql withArgumentsInArray:arrQuestIDs];
    };
    
    __weak typeof(self)weakSelf = self;
    ICRDatabaseFetchResultsBlock fetchResultsBlk = ^(NSArray *fetchedObjects) {
        __strong __typeof(weakSelf)strongSelf = weakSelf;
        
        strongSelf.m_arrQuestions = fetchedObjects;
        bIsQComplete = YES;
        
        if (bIsAComplete) {
            if (_openQuestAction) {
                _openQuestAction();
                self.openQuestAction = NULL;
            }
        }
    };
    
    ICRDataBaseController *dbCtrl = [ICRDataBaseController sharedController];
    [dbCtrl runFetchForClass:[ICRQuestion class]
                  fetchBlock:fetchBlk
           fetchResultsBlock:fetchResultsBlk];
    
    // StoreResult
    ICRDatabaseFetchBlock srFetchBlk = ^FMResultSet *(FMDatabase *db) {
        __strong __typeof(weakSelf)strongSelf = weakSelf;
        NSString * sql = [NSString stringWithFormat:@"SELECT * FROM %@ WHERE %@ = ?", [ICRStoreResult TableName], @"uuid"];
        return [db executeQuery:sql,strongSelf.m_patrolPlan.pID ];
    };
    
    ICRDatabaseFetchResultsBlock srFetchResultsBlk = ^(NSArray *fetchedObjects) {
        __strong __typeof(weakSelf)strongSelf = weakSelf;
        strongSelf.m_result = [fetchedObjects firstObject];
        
        NSMutableArray *mArr = [NSMutableArray array];
        for (NSDictionary *dict in _m_result.answers) {
            ICRAnswer *answer = [ICRAnswer DBObject];
            [answer praseFromLocalDict:dict];
            answer.bIsAnswered = YES;
            
            [mArr safeAddObject:answer];
        }
        
        
        strongSelf.m_arrAnswers = [mArr count] > 0 ? mArr : nil;
        
        bIsAComplete = YES;
        
        if (bIsQComplete) {
            if (_openQuestAction) {
                _openQuestAction();
                strongSelf.openQuestAction = NULL;
            }
        }
    };
    
    [dbCtrl runFetchForClass:[ICRStoreResult class]
                  fetchBlock:srFetchBlk
           fetchResultsBlock:srFetchResultsBlk];
}

#pragma mark - Private Method
- (void)cleanQuestions {
    self.m_imagePicker = nil;
    self.m_arrQuestions = nil;
    self.m_arrAnswers = nil;
    self.m_arrQuestViewCtrls = nil;
    self.m_baseRootViewCtrl = nil;
    self.m_result = nil;
    self.m_store = nil;
}

- (void)initLocaltionMgr {
    if ([CLLocationManager locationServicesEnabled]) {
        
        self.m_locationManager = [[CLLocationManager alloc] init];
        
        _m_locationManager.delegate = self;
        
        _m_locationManager.desiredAccuracy = kCLLocationAccuracyBest; //控制定位精度,越高耗电量越大。
        
        _m_locationManager.distanceFilter = 100; //控制定位服务更新频率。单位是“米”
        
        if ([_m_locationManager respondsToSelector:@selector(requestWhenInUseAuthorization)]) {
            [_m_locationManager requestAlwaysAuthorization];
        }
    }
}

- (void)fetchLocation {
    [_m_locationManager startUpdatingLocation];
}

#pragma mark - Public Method
- (ICRStoreResult *)getStoreResult {
    
    if (!_m_result) {
        _m_result=[[ICRStoreResult alloc]init];
        _m_result.store = @{@"uuid":[[ICRUserUtil sharedInstance] currentStoreID]};
//        _m_result.uuid = [[ICRUserUtil sharedInstance] mobileID];
        _m_result.uuid =self.m_patrolPlan.pID;
        _m_result.beginTime = [self.m_startTime httpParameterString];
        _m_result.user=@{@"uuid":[[ICRUserUtil sharedInstance] userId],@"code":[[ICRUserUtil sharedInstance] userCode],@"name":[[ICRUserUtil sharedInstance] userName]};
    }
    
    ICRStoreResult *storeR = self.m_result;
    storeR.endTime = [[NSDate date] httpParameterString];
    storeR.uploadTime=[[NSDate date] httpParameterString]   ;
    storeR.longitude = _m_nsLongtitude ? : @"";
    storeR.latitude = _m_nsLatitude ? : @"";
    storeR.remark = @"";
    
    NSMutableArray *mArr = [NSMutableArray array];
    for (ICRQuestionBaseViewController *vc in _m_arrQuestViewCtrls) {
        if (vc.m_answer.bIsAnswered) {
            [mArr safeAddObject:[vc.m_answer dictForLocalSave]];
        }
        else {
            break;
        }
    }
    
    storeR.answers = mArr;
    
    return storeR;
}

- (void)openQuestionVCFromViewControler:(UIViewController *)VC withPlan:(ICRPatrolPlan *)plan  {
    if (![VC isKindOfClass:[UIViewController class]] || !plan) {
        return;
    }
    
    [self fetchLocation];
    
    self.m_startTime = [NSDate date];
    
    self.m_baseRootViewCtrl = VC;
    
    __weak typeof(self)weakSelf = self;
    void(^block)(void) = ^(void) {
        __strong __typeof(weakSelf)strongSelf = weakSelf;
        NSMutableArray *arrViews = [NSMutableArray array];
        NSUInteger uiCount = [_m_arrQuestions count];
        NSUInteger uiIndex = 0;
        NSUInteger uiAIndex = 0;
        for (ICRQuestion *questE in strongSelf.m_arrQuestions) {
            ICRAnswer *answerE = [strongSelf.m_arrAnswers safeObjectAtIndex:uiIndex];
            ICRQuestionBaseViewController *qVC = [[ICRQuestionBaseViewController alloc] initWithQuestion:questE answer:answerE];
            qVC.m_uiIndex = uiIndex;
            qVC.title = [NSString stringWithFormat:@"巡店纪录(%@/%@)", @( uiIndex + 1 ), @( uiCount )];
            [arrViews addObject:qVC];
            
            uiIndex ++;
            
            if (answerE) {
                uiAIndex ++;
            }
        }
        
        strongSelf.m_arrQuestViewCtrls = [arrViews count] > 0 ? arrViews : nil;
        
        if (_m_arrQuestViewCtrls) {
            IBTUINavigationController *navCtrl = [[IBTUINavigationController alloc] initWithRootViewController:[arrViews firstObject]];
            
            NSArray *VCs = nil;
            if (uiAIndex < [arrViews count]) {
                VCs = [arrViews subarrayWithRange:NSMakeRange(0, uiAIndex + 1)];
            }
            else {
                ICRQResultViewController *rVC = [[ICRQResultViewController alloc] initWithPatrolPlan:self.m_patrolPlan andStoreResult:self.m_result];
                NSMutableArray *mArr =  [NSMutableArray array];
                [mArr addObjectsFromArray:arrViews];
                [mArr addObject:rVC];
                VCs = mArr;
            }
            
            navCtrl.viewControllers = VCs;
            
            [VC presentViewController:navCtrl animated:YES completion:NULL];
        }
    };
    
    self.openQuestAction = block;
    
    self.m_patrolPlan = plan;
}

- (UIViewController *)questionViewControlAtIndex:(NSUInteger)uiIndex {
    if (uiIndex < [_m_arrQuestViewCtrls count]) {
        return _m_arrQuestViewCtrls[ uiIndex ];
    }
    else {
        return nil;
    }
}

#pragma mark - CLLocationManagerDelegate
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations{
    CLLocation *currentPosition = [locations lastObject];
    
    self.m_nsLongtitude = [NSString stringWithFormat:@"%.3f",currentPosition.coordinate.longitude];
    self.m_nsLatitude = [NSString stringWithFormat:@"%.3f",currentPosition.coordinate.latitude];
    //_mylocationLongitude
    [_m_locationManager stopUpdatingLocation];
}

@end
