//
//  GTOAllPatrolPlanViewController.m
//  total
//  (巡检汇总)
//  Created by freecui on 15/9/15.
//  Copyright (c) 2015年 free. All rights reserved.
//

#import "GTOAllPatrolPlanViewController.h"
#import "GTOPatrolPlanInfoItemView.h" //
#import "GTOStoreItemView.h"
#import "GXFBottomView.h"
#import "GTOStoreItemView.h"
#import "GTOCategoryItemView.h"
#import "GTOStore.h"
#import "GTOPatrolPlan.h"
#import "GTOQuestion.h"
#import "ICRQuestionManager.h"
#import "GTODisplayResult.h"

#import "ICRAnswer.h"
#import "GTOPatrolPlanAllTopItem.h"
#import "GTOInspector.h"
#import "GTOProcessValue.h"

#import "GTOSignViewController.h"
#import "ICRStoreResult.h"
#import "GTOAlertInfoPatrolPlanViewController.h"
#import "ICRPatrolResultViewController.h"
#import <BaiduMapAPI/BMapKit.h>
//#define CELL_HEIGHT 80
typedef NS_ENUM(NSUInteger, viewTag){
    kCategoryTableVTag = 2,
    kNextbottomVTag
} ;
static NSString *cellIDCategory = @"cellIDCategory";
static NSString *cellIDPatrolPlanAllTop = @"cellIDPatrolPlanAllTop";
static NSString *cellIDStore = @"cellIDStore";
@interface GTOAllPatrolPlanViewController ()<GXFBottomViewDelegate,UITableViewDataSource,UITableViewDelegate,GTOPatrolPlanInfoItemViewDelegate,GTOAlertInfoPatrolPlanViewControllerDelegate,BMKLocationServiceDelegate,UIAlertViewDelegate>
@property (nonatomic, strong) UITableView *c_tableView;
@property (nonatomic, strong) UITableView *c_tableViewCategory;
@property (nonatomic, strong) GTOPatrolPlan *d_patroPlan;
@property (nonatomic, strong) NSArray * d_arrStors;
@property (nonatomic, strong) GTOStore *d_store;//当前的油站
@property (nonatomic, strong) NSArray *d_arrQuestonCategory;//问题区域数组
@property (nonatomic, strong) UIView *c_alertBgView;
@property (nonatomic, strong) UIView *c_alertInfo;
@property (nonatomic, strong) NSMutableArray *m_arrDisplayResults;//某个油站的不同区的答案数组
@property (nonatomic, strong) NSArray *m_arrAllStoresDisplayResults;//所有油站的不同区的答案数组
@property (nonatomic, strong) NSArray *m_arrInspectorys;
@property (strong, nonatomic) ICRStoreResult *m_result;

@property (nonatomic, strong) NSArray *m_arrCategorys; //同一任务中的问题都一样，所以category也一样

@property (nonatomic, strong) NSArray *d_arrProcessValues;//每个油站对应的进度


@property (nonatomic, strong) NSMutableArray *d_arrStoreResults;
@property (nonatomic, strong) GTOAlertInfoPatrolPlanViewController *alertInfoVC;
@property (nonatomic, strong) ICRStoreResult *d_currentStoreResult;//当前点击的列表的cell
//@property (nonatomic, assign) BOOL d_isClosed; //点击弹框的“关闭”按钮
@property (nonatomic, assign) NSInteger d_currentRow;
@property (strong, nonatomic) BMKLocationService *locService;
@property (nonatomic, assign) BOOL m_isAbandonLocation;//是否放弃定位
@property (nonatomic, assign) BOOL m_isAddAlertInfo;
@end

@implementation GTOAllPatrolPlanViewController
- (instancetype)initWithPatrolPlan:(GTOPatrolPlan *)patrolPlan {
    if (self = [super init]) {
        self.d_patroPlan = patrolPlan;
       
    }
    return self;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.title = @"巡检汇总";
   // [self initData];
    self.d_currentRow = -1;
    [self initSubViews];
}

- (void)viewWillAppear:(BOOL)animated {
    
    [self p_getStoreResults];
}
- (void)p_getStoreResults {
//        ICRDatabaseFetchBlock fetchBlk = ^FMResultSet *(FMDatabase *db) {
//            NSString *sql = [NSString stringWithFormat:@"SELECT *  FROM %@ WHERE %@=? ",[ICRStoreResult TableName],@"patrolUuid"];
//            return [db executeQuery:sql,_d_patroPlan.uuid];
//        };
//        __weak typeof (self)weakSelf = self;
//        ICRDatabaseFetchResultsBlock fetchResultsBlk = ^(NSArray *fetchedObjects) {
//            __strong __typeof(weakSelf)strongSelf = weakSelf;
//           
//          //  NSMutableArray *muarrStoreResult = [NSMutableArray array];
//            
//            strongSelf.d_arrStoreResults = fetchedObjects;
////            for(ICRStoreResult *storeResult in fetchedObjects) {
////                //storeResult.patrolUuid
////                //[muarrStoreResult addObject:question.category];
////            }
//
//        };
//    
//        ICRDataBaseController *dbCtrl = [ICRDataBaseController sharedController];
//        [dbCtrl runFetchForClass:[ICRStoreResult class]
//                      fetchBlock:fetchBlk
//               fetchResultsBlock:fetchResultsBlk];

    if (!self.d_arrStoreResults) {
        self.d_arrStoreResults = [@[]mutableCopy];
        
    } else {
        [self.d_arrStoreResults removeAllObjects];
    }
    
    ICRUserUtil *userU = [ICRUserUtil sharedInstance];
    for (int count =0; count < self.d_patroPlan.inspectors.count; count ++) { //
        NSDictionary *dictInspector = _d_patroPlan.inspectors[count];
        GTOInspector *inspector = [GTOInspector DBObject];
        [inspector praseFromJsonDict:dictInspector];
        
        ICRStoreResult *storeResult = [ICRStoreResult DBObject];
        storeResult.store_name = inspector.store_name;
        storeResult.store_code = inspector.store_code;
        storeResult.store_uuid =  inspector.store_uuid;
        storeResult.user_uuid = userU.f_user_uuid;
        storeResult.user_code = userU.f_user_code;
        storeResult.user_name = userU.f_user_name;
        storeResult.beginTime = _d_patroPlan.beginDate;
        storeResult.endTime = _d_patroPlan.endDate;
        storeResult.questions = _d_patroPlan.questions;
        storeResult.state = inspector.state == 1 ? kPatrolStoreStateSubmitted: kPatrolStoreStateUnfinished;//TODO
        storeResult.arrCategorys = _d_patroPlan.questionCategorys;
        storeResult.planState = _d_patroPlan.state;
        storeResult.plan_uuid = _d_patroPlan.uuid;
        
        
        if (inspector.state == 1) {
            [self.d_arrStoreResults addObject:storeResult];
           
           // storeResult.finishedQuestionNumber = storeResult.questions.count;
            [self.c_tableView reloadData];
        } else {
            ICRDatabaseFetchBlock fetchBlk = ^FMResultSet *(FMDatabase *db) {
                NSString *sql = [NSString stringWithFormat:@"SELECT *  FROM %@ WHERE %@=? AND %@=?",[ICRStoreResult TableName],@"plan_uuid",@"store_uuid"];
                return [db executeQuery:sql,_d_patroPlan.uuid,inspector.store_uuid];
            };
             __weak typeof (self)weakSelf = self;
            ICRDatabaseFetchResultsBlock fetchResultsBlk = ^(NSArray *fetchedObjects) {
                __strong __typeof(weakSelf)strongSelf = weakSelf;
                if (fetchedObjects) {
                    ICRStoreResult *storeR = fetchedObjects[0];
                    [strongSelf updateStoreResult:storeR patrolPlanUuid:_d_patroPlan.uuid storeUuid:inspector.store_uuid];
                } else {
                    [strongSelf updateStoreResult:storeResult patrolPlanUuid:_d_patroPlan.uuid storeUuid:inspector.store_uuid];
                }
            };
            ICRDataBaseController *dbCtrl = [ICRDataBaseController sharedController];
            [dbCtrl runFetchForClass:[ICRStoreResult class]
                          fetchBlock:fetchBlk
                   fetchResultsBlock:fetchResultsBlk];
        }
        
    }

    
}
- (void)appear {
    if (_d_currentRow > -1) {
        ICRStoreResult *storeRe = _d_arrStoreResults[_d_currentRow];
        if ((storeRe.state != kPatrolStoreStateSubmitted) && storeRe) {
            [self p_addAlerInfoPatrolPlanViewWithStoreResult:storeRe];
        }
    }
}
- (void)updateStoreResult: (ICRStoreResult *)storeR
           patrolPlanUuid: (NSString *)patroPlanUuid
                storeUuid: (NSString *)storeUuid{
    ICRStoreResult *storeResult = [ICRStoreResult DBObject];
    storeResult = storeR;
    ICRDatabaseFetchBlock fetchBlk = ^FMResultSet *(FMDatabase *db) {
        NSString *sql = [NSString stringWithFormat:@"SELECT *  FROM %@ WHERE %@=? AND %@=?",[ICRAnswer TableName],@"plan_uuid",@"store_uuid"];
        return [db executeQuery:sql,patroPlanUuid,storeUuid];
    };
    __weak typeof (self)weakSelf = self;
    ICRDatabaseFetchResultsBlock fetchResultsBlk = ^(NSArray *fetchedObjects) {
        __strong __typeof(weakSelf)strongSelf = weakSelf;
        NSMutableArray *answers = [@[]mutableCopy];
        for(ICRAnswer *answer in fetchedObjects) {
            [answers addObject:[answer dictForCommit]];
        }
        storeResult.answers = answers;

        NSMutableArray *muArrDisplayR = [@[]mutableCopy];
        for(NSString *category in storeResult.arrCategorys) {
            
            GTODisplayResult *displayR = [GTODisplayResult DBObject];
            //question
            NSMutableArray *muArrQ = [@[]mutableCopy];
            for(NSDictionary *dictQ in storeResult.questions) {
                if ([dictQ[@"category"] isEqualToString:category]) {
                    [muArrQ addObject:dictQ];
                }
            }
            //answer
            NSMutableArray *muArrA = [@[]mutableCopy];
            for(ICRAnswer *answer in fetchedObjects) {
                if ([answer.category isEqualToString:category]) {
                    [muArrA addObject:[answer dictForCommit]];
                }
            }
            
            displayR.category = category;
            displayR.arrAnswers = muArrA;
            displayR.arrQuestions = muArrQ;
            displayR.isDisplay = NO;
            [muArrDisplayR addObject:[displayR dictForCommit]];
            
        }
        
        if (!(storeR.state == kPatrolStoreStateSubmitted)) {
            if (storeResult.answers.count == storeResult.questions.count) {
                storeResult.state = kPatrolStoreStateUnsubmitted;
            } else if (storeResult.answers.count < storeResult.questions.count) {
                storeResult.state = kPatrolStoreStateUnfinished;
            } else {}
        }
        storeResult.arrDisplayResults = muArrDisplayR;
        [storeResult saveToDBWithHandleData:NULL complete:^{
//            if (self.m_isAddAlertInfo && (storeResult.state != kPatrolStoreStateSubmitted)) {
//                [self p_addAlerInfoPatrolPlanViewWithStoreResult:storeResult];
//            }
        } fail:NULL];

        [strongSelf.d_arrStoreResults addObject:storeResult];
//                        if (_d_currentRow > -1) {
//                        ICRStoreResult *storeRe = _d_arrStoreResults[_d_currentRow];
//                        if ((storeRe.state != kPatrolStoreStateSubmitted) && storeRe) {
//                            [self p_addAlerInfoPatrolPlanViewWithStoreResult:storeRe];
//                        }
//                        }
        [strongSelf.c_tableView reloadData];
    };
    
    ICRDataBaseController *dbCtrl = [ICRDataBaseController sharedController];
    [dbCtrl runFetchForClass:[ICRAnswer class]
                  fetchBlock:fetchBlk
           fetchResultsBlock:fetchResultsBlk];

}
- (void)initSubViews {

    self.c_tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, self.view.width , self.view.height - BottomViewHeight - NavigationBarHeight  ) style:UITableViewStylePlain];
    [self.c_tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:cellIDPatrolPlanAllTop];
    [self.c_tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:cellIDStore];
    
    self.c_tableView.dataSource = self;
    self.c_tableView.delegate = self;
    [self.view addSubview:_c_tableView];
   
    
    GXFBottomView *bottomV = [[GXFBottomView alloc]initOneButtonWithFrame:CGRectMake(0, _c_tableView.bottom, self.view.width, BottomViewHeight) buttonColor:GTO_RED_COLOR buttonTitle:@"返 回"];
    bottomV.delegate = self;
    [self.view addSubview:bottomV];
}




//UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    
    return  2;

}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
  
    return  section == 0 ? 1:_d_arrStoreResults.count;
   
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    UITableViewCell *cell ;
    
        if (indexPath.section == 0) {
        cell   = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIDPatrolPlanAllTop];
        } else {
        cell   = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIDStore];
        }
    
    

    [self configureCell:cell withTableView:tableView forRowAtIndexPath:indexPath];
    
    return cell;
}
- (void)configureCell:(UITableViewCell *)cell withTableView:(UITableView *)tableView
    forRowAtIndexPath:(NSIndexPath *)indexPath {
    UIView *contentView = cell.contentView;
    
       cell.selectionStyle = UITableViewCellSelectionStyleNone;
        if (indexPath.section == 0) {
            GTOPatrolPlanAllTopItem *topItem = [contentView viewWithClass:[GTOPatrolPlanAllTopItem class]];
            if (!topItem) {
                topItem = [[GTOPatrolPlanAllTopItem alloc]initWithFrame:contentView.bounds];
                [contentView addSubview:topItem];
            }
            
            CGFloat uploadedCount = 0;
            for (ICRStoreResult *result in _d_arrStoreResults) {
                if (result.state == kPatrolStoreStateSubmitted) {
                    uploadedCount++;
                }
            }
            _d_patroPlan.processLength = uploadedCount / _d_arrStoreResults.count;
            
            [topItem updateWithPatrolPlan:_d_patroPlan];
            
        } else {
            GTOStoreItemView *storeItem = [contentView viewWithClass:[GTOStoreItemView class]];
            
            if (!storeItem) {
                storeItem = [[GTOStoreItemView alloc]initWithFrame:CGRectMake(0, 0, ScreenSize.width, contentView.height)];//contentView.bounds];
                ///storeItem.delegate = self;
                [contentView addSubview:storeItem];
            }
            ICRStoreResult *storeR = _d_arrStoreResults[indexPath.row];
            [storeItem updateWithStoreResult:storeR];

        }

}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    UIView *view;
    CGFloat padding = 10;
    static NSString *headerID;
    CGRect rect = CGRectMake(0, 0, tableView.width, 50);
    if (section == 0) {
        headerID = @"addressID";
        view = [tableView dequeueReusableHeaderFooterViewWithIdentifier:headerID];
        if (!view) {
            view = [[UIView alloc]initWithFrame:rect];//tableView.tableHeaderView.bounds];
            CGRect rect = CGRectMake(padding, 0, 150, view.height);
            IBTUILabel *lblTitle = [[IBTUILabel alloc]initWithFrame:rect text:_d_patroPlan.name font:[UIFont systemFontOfSize:18] tintColor:[UIColor blackColor] backgroundColor:XXFBgColor textAlignment:NSTextAlignmentLeft];
            
            UIView *viewAddress = [[UIView alloc]initWithFrame:CGRectMake(view.width - 10 - 150, 0, 150, lblTitle.height)];
            rect = CGRectMake(0, 0, 100, lblTitle.height);//
//            IBTUILabel *lblAddress = [[IBTUILabel alloc]initWithFrame:rect text:@"我的位置" font:[UIFont systemFontOfSize:16] tintColor:[UIColor blackColor] backgroundColor:XXFBgColor  textAlignment:NSTextAlignmentRight];
//            UIImageView *imgV = [[UIImageView alloc]initWithFrame:CGRectMake(lblAddress.right, 0, 40, lblAddress.height)];
//            imgV.image = [UIImage imageNamed:@""];
//            [viewAddress addSubview:lblAddress];
//            [viewAddress addSubview:imgV];
            [view addSubview:lblTitle];
            [view addSubview:viewAddress];
        }
    } else if (section == 1) {
        headerID = @"stateID";
        view = [tableView dequeueReusableHeaderFooterViewWithIdentifier:headerID];
        if (!view) {
            view = [[UIView alloc]initWithFrame:rect];//tableView.tableHeaderView.bounds];
            CGRect rect = CGRectMake(padding, 0, 100, view.height);
            UILabel *lblState = [[IBTUILabel alloc]initWithFrame:rect text:@"油站列表" font:[UIFont systemFontOfSize:18] tintColor:[UIColor blackColor] backgroundColor:XXFBgColor  textAlignment:NSTextAlignmentLeft];
            [view addSubview:lblState];
        }
        
    }
    view.backgroundColor = XXFBgColor;
    return view;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {

    return 50;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {

    return indexPath.section == 0 ? 120 : 80;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {

    self.d_currentRow = indexPath.row;
    if(indexPath.section < 1) return;
    ICRStoreResult *storeR = _d_arrStoreResults[indexPath.row];
    if (_d_currentStoreResult) {
        _d_currentStoreResult = nil;
    }
    self.d_currentStoreResult = storeR;

        ICRDatabaseFetchBlock fetchBlk = ^FMResultSet *(FMDatabase *db) {
            NSString *sql = [NSString stringWithFormat:@"SELECT *  FROM %@ WHERE %@=? AND %@=?",[ICRStoreResult TableName],@"plan_uuid",@"store_uuid"];
            return [db executeQuery:sql,_d_patroPlan.uuid,_d_currentStoreResult.store_uuid];
        };
        __weak typeof (self)weakSelf = self;
        ICRDatabaseFetchResultsBlock fetchResultsBlk = ^(NSArray *fetchedObjects) {
            __strong __typeof(weakSelf)strongSelf = weakSelf;
            if (fetchedObjects) {
//                storeR.planState == kPatrolPlanStatusProcessing
                ICRStoreResult *storeR = fetchedObjects[0];
                if(!(storeR.planState == kPatrolPlanStatusProcessing)){
                    ICRPatrolResultViewController *resultVC = [[ICRPatrolResultViewController alloc]initWithStoreResult:storeR andPatrolPlan:_d_patroPlan];
                    [self PushViewController:resultVC animated:YES];
                    return ;
                }
                if (storeR.state == kPatrolStoreStateUnfinished  ) {
                    if (!storeR.latitude && !storeR.longitude) {
                        [self locatedPosition];
                    } else {
                        [self p_addAlerInfoPatrolPlanViewWithStoreResult:storeR];
                    }
                    
                } else {
                    ICRPatrolResultViewController *resultVC = [[ICRPatrolResultViewController alloc]initWithStoreResult:storeR andPatrolPlan:_d_patroPlan];
                    resultVC.result = storeR;
                    [self PushViewController:resultVC animated:YES];
                }
            } else {
                if (_d_currentStoreResult.state == kPatrolStoreStateSubmitted) {
                    [self p_httpGetStoreResultWithStoreUuid:_d_currentStoreResult.store_uuid ofRowAtIndexPath:indexPath];
                } else {
                    ICRPatrolResultViewController *resultVC = [[ICRPatrolResultViewController alloc]initWithStoreResult:_d_currentStoreResult andPatrolPlan:_d_patroPlan];
                    
                    [self PushViewController:resultVC animated:YES];
                }
                
            }
        };
        ICRDataBaseController *dbCtrl = [ICRDataBaseController sharedController];
        [dbCtrl runFetchForClass:[ICRStoreResult class]
                      fetchBlock:fetchBlk
               fetchResultsBlock:fetchResultsBlk];
}
- (void)p_addAlerInfoPatrolPlanViewWithStoreResult: (ICRStoreResult *)storeResult   {
    self.m_isAddAlertInfo = YES;
    if (_alertInfoVC) {
        [_alertInfoVC.view removeFromSuperview];
        _alertInfoVC = nil;
    }
    
    GTOAlertInfoPatrolPlanViewController *alertInfoVC = [[GTOAlertInfoPatrolPlanViewController alloc]initWithStoreResult:storeResult andPatrolPlan: _d_patroPlan ];
    self.alertInfoVC = alertInfoVC;
    alertInfoVC.delegate = self;
    [[UIApplication sharedApplication].keyWindow addSubview:_alertInfoVC.view];
}
- (void)p_httpGetStoreResultWithStoreUuid: (NSString *)storeUuid ofRowAtIndexPath:(NSIndexPath *)indexPath {
    __weak typeof(self)weakSelf = self;
    void(^succ)(id) = ^(id data) {
        [IBTLoadingView hideHUDWithText:nil];
        __strong __typeof(weakSelf)strongSelf = weakSelf;
        if (![data[@"success"] integerValue] == 1) {
            [IBTLoadingView showTextOnly:data[@"message"] inView:self.view];
        } else {
            NSDictionary *dict = data[@"data"];
            ICRStoreResult *storeResult = [ICRStoreResult DBObject];
            [storeResult praseFromJsonDict:dict];
            
             ICRStoreResult *originSR = _d_arrStoreResults[indexPath.row];
            /*
             storeResult.questions = _d_patroPlan.questions;
             storeResult.state = inspector.state;
             storeResult.arrCategorys = _d_patroPlan.questionCategorys;
             */
            storeResult.questions = originSR.questions;
            storeResult.state = originSR.state;
            storeResult.arrCategorys = originSR.arrCategorys;
            storeResult.plan_uuid = _d_patroPlan.uuid;
           
            
            NSMutableArray *muArrDisplayR = [@[]mutableCopy];
            for(NSString *category in storeResult.arrCategorys) {
                
                GTODisplayResult *displayR = [GTODisplayResult DBObject];
                //question
                NSMutableArray *muArrQ = [@[]mutableCopy];
                //answer
                NSMutableArray *muArrA = [@[]mutableCopy];
                for(NSDictionary *dictQ in storeResult.questions) {
                    GTOQuestion *question = [GTOQuestion DBObject];
                    [question praseFromJsonDict:dictQ];
                    if ([question.category isEqualToString:category]) {
                        [muArrQ addObject:dictQ];
                        for(NSDictionary *dictAnswer in storeResult.answers) {
                            ICRAnswer *answer = [ICRAnswer DBObject];
                            [answer praseFromJsonDict:dictAnswer];
                            answer.store_uuid = originSR.store_uuid;
                            answer.plan_uuid = originSR.plan_uuid;
                            if (answer.resultAttachments.count > 0) {
                                answer.bIsDownLoadImgs = YES;
                            }
                            if ([answer.questionUuid isEqualToString:question.uuid]) {
                                answer.type = question.type;
                                answer.category = question.category;
                                [answer saveToDBWithHandleData:NULL complete:NULL fail:NULL];
                                [muArrA addObject:[answer dictForCommit]];
                            }
                        }
                    }
                }

                
                
                displayR.category = category;
                displayR.arrAnswers = muArrA;
                displayR.arrQuestions = muArrQ;
                displayR.isDisplay = NO;
                [muArrDisplayR addObject:[displayR dictForCommit]];
                if (displayR.arrAnswers.count == displayR.arrQuestions.count) {
                    storeResult.state = kPatrolStoreStateSubmitted;
                } else {
                    storeResult.state = kPatrolStoreStateUnfinished;
                }
            }

            
            storeResult.arrDisplayResults = muArrDisplayR;
            [self.d_arrStoreResults replaceObjectAtIndex:indexPath.row withObject:storeResult];
            self.d_currentStoreResult = storeResult;
            [self.d_currentStoreResult saveToDBWithHandleData:NULL complete:^{
                ICRPatrolResultViewController *resultVC = [[ICRPatrolResultViewController alloc]initWithStoreResult:_d_currentStoreResult andPatrolPlan:_d_patroPlan];
                [self PushViewController:resultVC animated:YES];
//                //[self p_addAlerInfoPatrolPlanViewWithStoreResult:_d_currentStoreResult];
//                BOOL isAllowed = [self nowInTimeDuringMinTime:_d_currentStoreResult.beginTime maxTime:_d_currentStoreResult.beginTime];
//                BOOL conditionPlanStatus = !(_d_currentStoreResult.planState == kPatrolPlanStatusProcessing) || !isAllowed;
//                BOOL condition = _d_currentStoreResult.state == kPatrolStoreStateSubmitted || _d_currentStoreResult.state == kPatrolStoreStateUnsubmitted;
//                if (condition || conditionPlanStatus) {
//                    ICRPatrolResultViewController *resultVC = [[ICRPatrolResultViewController alloc]initWithStoreResult:_d_currentStoreResult andPatrolPlan:_d_patroPlan];
//                    [self PushViewController:resultVC animated:YES];
//                } else {
//                    [self p_addAlerInfoPatrolPlanViewWithStoreResult:_d_currentStoreResult];
//                }

            } fail:NULL];
            
        }
    };
    void(^fail)(id) = ^(id data) {
        [IBTLoadingView hideHUDWithText:nil];
        [IBTLoadingView showTips:data];
    };
    [IBTLoadingView showProgressLabel:@"正在加载..."];
    ICRHTTPController *httpC = [ICRHTTPController sharedController];
    [httpC doGetStoreResultWithPlanID:_d_patroPlan.uuid storeID:storeUuid success:succ failure:fail];
}

//#pragma GTOStoreItemDelegate
//- (void)storeItemView:(GTOStoreItemView *)storeItemView {
//    GTOSignViewController *signVC = [[GTOSignViewController alloc]init];
//    signVC.latitudeX = _d_currentStoreResult.latitude;
//    signVC.longitudeY = _d_currentStoreResult.longitude;
//    signVC.locatedTime = _d_currentStoreResult.locatedTime;
//    
//    [self PushViewController:signVC animated:YES];
//}
#pragma GTOPatrolPlanInfoItemViewDelegate
- (void)patrolPlanInfoItemViewLocationWithLongitude:(CGFloat)longitude andLatitude:(CGFloat)latitude {

}

#pragma GXFBottomViewDelegate
- (void)bottomView:(GXFBottomView *)bottomView oneButtonClicked:(UIButton *)oneBtn {
    [self PopViewControllerAnimated:YES];
}

#pragma GTOAlertInfoPatrolPlanViewControllerDelegate


- (void)alertInfoPatrolPlanViewController: (GTOAlertInfoPatrolPlanViewController *)alertInfoPatrolPlan closeClickedWithBtton:(UIButton *)btn {
    if (_alertInfoVC) {
        [_alertInfoVC.view removeFromSuperview];
        _alertInfoVC = nil;
    }
   
}
- (void)alertInfoPatrolPlanViewController: (GTOAlertInfoPatrolPlanViewController *)alertInfoPatrolPlan seeResultClickedWithBtton:(UIButton *)btn {
    if(_d_currentStoreResult.state == 0)
        {
            _d_currentStoreResult = _d_arrStoreResults[_d_currentRow];
        }
   ICRPatrolResultViewController *resultVC = [[ICRPatrolResultViewController alloc]initWithStoreResult:_d_currentStoreResult andPatrolPlan:_d_patroPlan];
    
    if (_alertInfoVC) {
        [_alertInfoVC.view removeFromSuperview];
        _alertInfoVC = nil;
    }
    [self PushViewController:resultVC animated:YES];
}
- (void)alertInfoPatrolPlanViewController: (GTOAlertInfoPatrolPlanViewController *)alertInfoPatrolPlan nextClickedWithBtton:(UIButton *)btn {
//    [self permitAnswerProblems];
//    if (!(_d_currentStoreResult.planState == kPatrolPlanStatusProcessing)) {
//        [IBTLoadingView showTextOnly:@"任务状态不在执行中，不能填写"];
//        return;
//    }
//    BOOL isAllowed = [self nowInTimeDuringMinTime:_d_currentStoreResult.beginTime maxTime:_d_currentStoreResult.endTime];
//    if (!isAllowed) {
//        [IBTLoadingView showTextOnly:@"不在计划时间范围内，不能填写"];
//        return;
//    }
    
    BOOL isAllFinished = YES;
    for(NSDictionary *dictR in _d_currentStoreResult.arrDisplayResults) {
         GTODisplayResult *displayR = [GTODisplayResult DBObject];
        [displayR praseFromJsonDict:dictR];
        if (displayR.arrAnswers.count <  displayR.arrQuestions.count) {
            ICRQuestionManager *mgr = [ICRQuestionManager sharedManager];
            mgr.m_category = displayR.category;//alertInfoPioneering.d_arrCategorys[indexPath.row];
            mgr.m_store_uuid = _d_currentStoreResult.store_uuid;
            mgr.m_plan_uuid = _d_patroPlan.uuid;
            [mgr openQuestionVCFromViewControler:self withStoreResult:_d_currentStoreResult];
            [self alertInfoPatrolPlanViewController:alertInfoPatrolPlan closeClickedWithBtton:nil];
            isAllFinished = NO;
            break;
        }
    }
    
    if (isAllFinished) {
        NSDictionary *dictR = [_d_currentStoreResult.arrDisplayResults lastObject];
        GTODisplayResult *displayR = [GTODisplayResult DBObject];
        [displayR praseFromJsonDict:dictR];
        ICRQuestionManager *mgr = [ICRQuestionManager sharedManager];
        mgr.m_category = displayR.category;//alertInfoPioneering.d_arrCategorys[indexPath.row];
        mgr.m_store_uuid = _d_currentStoreResult.store_uuid;
        mgr.m_plan_uuid = _d_patroPlan.uuid;
        [mgr openQuestionVCFromViewControler:self withStoreResult:_d_currentStoreResult];
        [self alertInfoPatrolPlanViewController:alertInfoPatrolPlan closeClickedWithBtton:nil];

    }
    
}
- (void)alertInfoPatrolPlanViewController: (GTOAlertInfoPatrolPlanViewController *)alertInfoPatrolPlan didSelectRowAtIndexPath: (NSIndexPath *)indexPath {
    [self permitAnswerProblems];
//    if (!(_d_currentStoreResult.planState == kPatrolPlanStatusProcessing)) {
//        [IBTLoadingView showTextOnly:@"任务状态不在执行中，不能填写"];
//        return;
//    }
//    BOOL isAllowed = [self nowInTimeDuringMinTime:_d_currentStoreResult.beginTime maxTime:_d_currentStoreResult.endTime];
//    if (!isAllowed) {
//        [IBTLoadingView showTextOnly:@"不在计划时间范围内，不能填写"];
//        return;
//    }

    
    ICRQuestionManager *mgr = [ICRQuestionManager sharedManager];
    GTODisplayResult *displayR = [GTODisplayResult DBObject];
    [displayR praseFromJsonDict:_d_currentStoreResult.arrDisplayResults[indexPath.row]];
    mgr.m_category = displayR.category;//alertInfoPioneering.d_arrCategorys[indexPath.row];
    mgr.m_store_uuid = _d_currentStoreResult.store_uuid;
    mgr.m_plan_uuid = _d_patroPlan.uuid;
    [mgr openQuestionVCFromViewControler:self withStoreResult:_d_currentStoreResult];
    
    [self alertInfoPatrolPlanViewController:alertInfoPatrolPlan closeClickedWithBtton:nil];

}
- (void)permitAnswerProblems{
    if (!(_d_currentStoreResult.planState == kPatrolPlanStatusProcessing)) {
        [IBTLoadingView showTextOnly:@"不在计划时间范围内，不能填写"];
        return;
    }
}
- (BOOL)nowInTimeDuringMinTime: (NSString *)minTime
                        maxTime: (NSString *)maxTime{
    NSTimeInterval nowInterl = [[NSDate date]timeIntervalSince1970];
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd"];//HH:mm:ss"];
    NSDate *minDate = [dateFormatter dateFromString:minTime];
    NSDate *maxDate = [dateFormatter dateFromString:maxTime];
   // NSDate *date = [dateFormatter dateFromString:@"2015-12-01"];

    NSTimeInterval minTimeInterl = [minDate timeIntervalSince1970];
    NSTimeInterval maxTimeInterl = [maxDate timeIntervalSince1970];
    if (nowInterl >= minTimeInterl && nowInterl <= maxTimeInterl) {
        return YES;
    } else {
        return NO;
    }
}
- (void)locatedPosition {
    if (!self.locService) {
        self.locService = [[BMKLocationService alloc]init];
        self.locService.delegate = self;
       
    }
    [IBTLoadingView showProgressLabel:@"正在获取位置"];
    [_locService startUserLocationService];
//    [IBTLoadingView showProgressLabel:@"正在获取位置"];
//    [_locService startUserLocationService];
//    BOOL condition = !_d_currentStoreResult.latitude && !_d_currentStoreResult.longitude
//    && (_d_currentStoreResult.state != kPatrolStoreStateSubmitted) && !_m_isAbandonLocation;
//    if (condition) {
//        if (!self.locService) {
//            self.locService = [[BMKLocationService alloc]init];
//            self.locService.delegate = self;
//            
//        }
//        
//        [IBTLoadingView showProgressLabel:@"正在获取位置"];
//        [_locService startUserLocationService];
//
//    } else {
//        [self p_addAlerInfoPatrolPlanViewWithStoreResult:_d_currentStoreResult];
//    }
}
#pragma BMKLocationServiceDelegate
- (void)willStartLocatingUser {
    NSLog(@"start locate");
}

- (void)didFailToLocateUserWithError:(NSError *)error
{
    [IBTLoadingView hideHUDWithText:nil];
    [_locService stopUserLocationService];
    UIAlertView *alertV = [[UIAlertView alloc]initWithTitle:@"目前无法定位" message:@"是否放弃定位" delegate:self cancelButtonTitle:@"放弃定位" otherButtonTitles:@"再次尝试", nil];
    [alertV show];
    NSLog(@"location error");
}
- (void)didUpdateBMKUserLocation:(BMKUserLocation *)userLocation {
     //[IBTLoadingView hideHUDForView:self.view];
    [_locService stopUserLocationService];
        NSLog(@"didUpdateUserLocation lat %f,long %f",userLocation.location.coordinate.latitude,userLocation.location.coordinate.longitude);
    NSString *latitude = [NSString stringWithFormat:@"%.6f",userLocation.location.coordinate.latitude];
    NSString *longitude = [NSString stringWithFormat:@"%.6f",userLocation.location.coordinate.longitude];
    _d_currentStoreResult.latitude = latitude;
    _d_currentStoreResult.longitude = longitude;
    _d_currentStoreResult.locatedTime = [[NSDate date] httpParameterString];
    [self httpGetNearStore];
}
- (void)httpGetNearStore {
    void(^succ)(id) = ^(id data) {
//        CLog(@"%@",data);
        if ([data[@"success"] integerValue]== 1) {
            NSArray *arrStores = data[@"data"];
            if (!arrStores) {
                NSDictionary *dictStore = arrStores[0];
                _d_currentStoreResult.realStore_uuid = dictStore[@"uuid"];
                _d_currentStoreResult.realStore_code = dictStore[@"code"];
                _d_currentStoreResult.realStore_name = dictStore[@"name"];
            }
            [_d_currentStoreResult saveToDBWithHandleData:NULL complete:^{
                [IBTLoadingView hideHUDWithText:nil];
//                [_locService stopUserLocationService];
                [self p_addAlerInfoPatrolPlanViewWithStoreResult:_d_currentStoreResult];
            } fail:NULL];
        } else {
            [_d_currentStoreResult saveToDBWithHandleData:NULL complete:^{
                [IBTLoadingView hideHUDWithText:nil];
                //                [_locService stopUserLocationService];
                [self p_addAlerInfoPatrolPlanViewWithStoreResult:_d_currentStoreResult];
            } fail:NULL];

        }
    };
    void(^fail)(id) = ^(id data) {
//        CLog(@"%@",data);
        [IBTLoadingView hideHUDWithText:nil];
        [_d_currentStoreResult saveToDBWithHandleData:NULL complete:^{
            [IBTLoadingView hideHUDWithText:nil];
            //                [_locService stopUserLocationService];
            [self p_addAlerInfoPatrolPlanViewWithStoreResult:_d_currentStoreResult];
        } fail:NULL];

    };
    ICRHTTPController *httpC = [ICRHTTPController sharedController];
    [httpC getNearStoreWithLongitude:_d_currentStoreResult.longitude andLatitude:_d_currentStoreResult.latitude success:succ failure:fail];
    
    
}
- (void)didStopLocatingUser
{
    NSLog(@"stop locate");
}
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    switch (buttonIndex) {
        case 0:
        {
            [_locService stopUserLocationService];
            NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(timeFired:) userInfo:NULL repeats:NO];
            self.m_isAbandonLocation = YES;
//            [self p_addAlerInfoPatrolPlanViewWithStoreResult:_d_currentStoreResult];
            
        }
            break;
        case 1:
        {
            self.m_isAbandonLocation = NO;
            [self locatedPosition];
        }
            break;
        default:
            break;
    }
}
- (void)timeFired: (NSTimer *)timer {
     [self p_addAlerInfoPatrolPlanViewWithStoreResult:_d_currentStoreResult];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}



@end
