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

#import "ICRPatrolResultViewController.h"
#import "ICRQuestionHelperView.h"
#import "ICRAttachmentView.h"
#import "GTODisplayResult.h"
#import "GTOPatrolPlanResultHeaderItem.h"
#import "GTOPatrolPlanResultProblemItem.h"
#import "GTOLicenceResultTopCellContentView.h"
#import "GXFBottomView.h"
#import "GTOLicenceResultHeaderContentView.h"

///avatar
#import "ICRStoreResult.h"
#import "GTOPatrolPlanResultTopItem.h"
#import "ICRQuestionBaseViewController.h"
#import "GTOSubmitPlan.h"
#import "ICRAnswer.h"
#import "GTOSubmitPlanAnswer.h"
#import "ICRPostAttachment.h"
#import "GTOPositionMapViewController.h"
#import "ICRQuestionManager.h"
#define GXF_DETAIL_COLOR        HexColor(@"888888")
#define GXF_CONTENT_COLOR       HexColor(@"444444")

#define KEY_IS_DISPLAY @"isDisplay"
typedef NS_ENUM(NSUInteger,bottomViewTag) {
    kBottomViewOneBackTag = 0,
    kBottomViewOneSubmitTag ,
};

static NSString *cellIDTop = @"topCell";
static NSString *cellIDQuestion = @"questionCell";
//只有标题
static NSString *headerID = @"headerID";
//可以点击(存放问题的header)
static NSString *headerItem = @"headerItem";

@interface ICRPatrolResultViewController ()
<UITextFieldDelegate,
UITableViewDataSource,
UITableViewDelegate, GTOPatrolPlanResultHeaderItemDelegate,
GXFBottomViewDelegate>
@property(strong, nonatomic) ICRQuestionHelperView *m_helperView;
@property(nonatomic, strong) NSIndexPath *m_clickedIndexPath;;
/////
@property(strong, nonatomic) ICRStoreResult *d_storeResult;
@property (strong, nonatomic) GTOPatrolPlan *d_patrolPlan;
@property(nonatomic, strong) UITableView *c_tableView;
@property (nonatomic, strong) NSMutableArray *d_arrPostAttachments;

@end

@implementation ICRPatrolResultViewController

#pragma mark - Life Cycle
- (instancetype)initWithStoreResult:(ICRStoreResult *)storeResult
                      andPatrolPlan: (GTOPatrolPlan *)patrolPlan {
    self = [super init];
    if (!self) {
        return nil;
    }
    if ([storeResult isKindOfClass:[storeResult class]]) {
        self.d_storeResult = storeResult;
    }
    self.d_patrolPlan = patrolPlan;
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.title = @"工程巡检结果";
    [self initSubViews];
    
}
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear: animated];
    [self updateAnswer];
}
- (void)updateAnswer {
    if (!self.m_clickedIndexPath) {
        return;
    }
    ICRStoreResult *storeResult = [ICRStoreResult DBObject];
    storeResult = _d_storeResult;
    
    ICRDatabaseFetchBlock fetchBlk = ^FMResultSet *(FMDatabase *db) {
        NSString *sql = [NSString stringWithFormat:@"SELECT *  FROM %@ WHERE %@=? AND %@=? ",[ICRAnswer TableName],@"plan_uuid",@"store_uuid"];//AND %@=? ,@"category"
        return [db executeQuery:sql,_d_storeResult.plan_uuid,_d_storeResult.store_uuid];//,displayR.category
    };
    __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;
            for(NSDictionary *dict in _d_storeResult.arrDisplayResults){
                GTODisplayResult *orDisplayR = [GTODisplayResult DBObject];
                [orDisplayR praseFromJsonDict:dict];
                if ([orDisplayR.category isEqualToString:displayR.category]) {
                    displayR.isDisplay = orDisplayR.isDisplay;
                    break;
                }
                
            }
            
            [muArrDisplayR addObject:[displayR dictForCommit]];
            
        }
        
        if (!(storeResult.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:^{
            strongSelf.d_storeResult = storeResult;
            [_c_tableView reloadData];
        } fail:NULL];
        
    };
    
    ICRDataBaseController *dbCtrl = [ICRDataBaseController sharedController];
    [dbCtrl runFetchForClass:[ICRAnswer class]
                  fetchBlock:fetchBlk
           fetchResultsBlock:fetchResultsBlk];
}
- (void)initSubViews {
    //tableView
    self.c_tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, self.view.width, self.view.height - 60 - 64) style:UITableViewStylePlain];
    self.c_tableView.delegate = self;
    self.c_tableView.dataSource = self;
    [self.c_tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:cellIDTop];
    [self.c_tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:cellIDQuestion];
    [self.c_tableView registerClass:[UITableViewHeaderFooterView class] forHeaderFooterViewReuseIdentifier:headerID];
    [self.view addSubview:_c_tableView];
    
    //bottomView
    
    CGRect rect = CGRectMake(0, _c_tableView.bottom, self.view.width, 40);
    GXFBottomView * bottomV = [[GXFBottomView alloc] initOneButtonWithFrame:rect buttonColor:GTO_RED_COLOR buttonTitle:@""];
    if(_d_storeResult.state == kPatrolStoreStateUnsubmitted) {
        bottomV.tag = kBottomViewOneSubmitTag;
        [bottomV.f_oneBtn setTitle:@"提交" forState:UIControlStateNormal];
    } else {
        bottomV.tag = kBottomViewOneBackTag;
        [bottomV.f_oneBtn setTitle:@"返回" forState:UIControlStateNormal];
    }
    
    bottomV.backgroundColor = XXFBgColor;
    bottomV.delegate = self;
    
    [self.view addSubview:bottomV];
}


#pragma UITableViewDataSource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 2 + _d_storeResult.arrDisplayResults.count;//_d_arrDisplayResults.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    CLog(@"indexpath section = %ld", section);
    if (section == 0) {
        return 1;
    } else if (section == 1) {
        return 0;
    } else {
        for (int count = 0; count < _d_storeResult.arrDisplayResults.count; count++) {  //
            if (section == count + 2) {
                GTODisplayResult *displayR = [GTODisplayResult DBObject];
                [displayR praseFromJsonDict:_d_storeResult.arrDisplayResults[count]];
                return displayR.isDisplay ? displayR.arrQuestions.count : 0;
            }
        }
        
        return 0;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    UITableViewCell *cell;
    if (indexPath.section == 0) {
        cell = [tableView dequeueReusableCellWithIdentifier:cellIDTop];
    } else if (indexPath.section > 1) {
        cell = [tableView dequeueReusableCellWithIdentifier:cellIDQuestion];
    } else {
        return nil;
    }
    if(cell) {
        [self configureCell:cell forRowAtIndexPath:indexPath];
        
    }
    
    return cell;
}

- (void)configureCell:(UITableViewCell *)cell
    forRowAtIndexPath:(NSIndexPath *)indexPath {
    UIView *contentView = cell.contentView;
    
    if (indexPath.section == 0) {
        GTOPatrolPlanResultTopItem *topItem = [contentView viewWithClass:[GTOPatrolPlanResultTopItem class]];
        if (!topItem) {
            topItem = [[GTOPatrolPlanResultTopItem alloc] initWithFrame:contentView.bounds];
            [topItem autoresizingWithStrechFullSize];
            [contentView addSubview:topItem];
        }
        [topItem updateWithPatrolPlan:_d_patrolPlan storeResult:_d_storeResult];
        
    } else if (indexPath.section >= 2) {
        
        GTOPatrolPlanResultProblemItem *problemItem = [contentView viewWithClass:[GTOPatrolPlanResultProblemItem class]];
        
        if (!problemItem) {
            problemItem = [[GTOPatrolPlanResultProblemItem alloc] initWithFrame:contentView.bounds];
            
            problemItem.m_modifyBtn.tag = indexPath.row;
            [problemItem.m_modifyBtn addTarget:self action:@selector(modifyClicked:) forControlEvents:UIControlEventTouchUpInside];
            
            [cell.contentView addSubview:problemItem];
        }
        
        GTODisplayResult *displayR = [GTODisplayResult DBObject];
        [displayR praseFromJsonDict:_d_storeResult.arrDisplayResults[indexPath.section - 2]];
        
        GTOQuestion *question = [GTOQuestion DBObject];
        [question praseFromJsonDict:displayR.arrQuestions[indexPath.row]];
        [self uploadePatrolPlanResultProblemItemAnswer:problemItem question:question cellForRowAtIndexPath:indexPath];
        
        //        ICRAnswer *answer = [ICRAnswer DBObject];
        //        [answer praseFromJsonDict:displayR.arrAnswers[indexPath.row]];
        //        for (NSDictionary *dictQues in displayR.arrQuestions) {
        //            GTOQuestion *question = [GTOQuestion DBObject];
        //            [question praseFromJsonDict:dictQues];
        //            if ([question.uuid isEqualToString:answer.questionUuid])
        //                [problemItem updateWithQuestion:question answer:nil index:indexPath.row];
        //        }
        
    }
    
    
}
- (void)uploadePatrolPlanResultProblemItemAnswer: (GTOPatrolPlanResultProblemItem *)problemItem question: (GTOQuestion *)question cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    ICRDatabaseFetchBlock fetchBlk = ^FMResultSet *(FMDatabase *db) {
        NSString * sql = [NSString stringWithFormat:@"SELECT *  FROM %@ WHERE %@ = ? AND  %@ = ? AND  %@ = ? ", [ICRAnswer TableName], @"plan_uuid",@"store_uuid",@"questionUuid" ];
        //答案的排序按照问题的uuid来，（此事的排序关系到结果页中答案的显示，按道理应该是根据答题的顺序，是不是后台给的问题应该排序？？？？？）
        NSLog(@"%@",sql);
        return [db executeQuery:sql,_d_storeResult.plan_uuid,_d_storeResult.store_uuid,question.uuid];
    };
    
    __weak typeof(self)weakSelf = self;
    ICRDatabaseFetchResultsBlock fetchResultsBlk = ^(NSArray *fetchedObjects) {
        __strong __typeof(weakSelf)strongSelf = weakSelf;
        
        if (fetchedObjects) {
            ICRAnswer *answer = fetchedObjects[0];
            [problemItem updatePatrolWithQuestion:question answer:answer index:indexPath.row];
        } else {
            [problemItem updatePatrolWithQuestion:question answer:nil index:indexPath.row];
        }
        
    };
    
    ICRDataBaseController *dbCtrl = [ICRDataBaseController sharedController];
    [dbCtrl runFetchForClass:[ICRAnswer class]
                  fetchBlock:fetchBlk
           fetchResultsBlock:fetchResultsBlk];
}
#pragma UITableViewDelegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section <= 1)
        return;
    //    NSInteger problemIndex = 0;
    //    for (int i = 0; i <= indexPath.section - 2; i++) {
    //        problemIndex += [_d_storeResult.arrDisplayResults[indexPath.section - 2]count]+ indexPath.row + 1;
    //    }
    self.m_clickedIndexPath = indexPath;
    GTODisplayResult *displayR = [GTODisplayResult DBObject];
    [displayR praseFromJsonDict:_d_storeResult.arrDisplayResults[indexPath.section - 2]];
    GTOQuestion *question = [GTOQuestion DBObject];
    [question praseFromJsonDict:displayR.arrQuestions[indexPath.row]];
    
    BOOL isNotEdit = NO;
    //    BOOL isAllowed = [GTOCommonTools nowInTimeDuringMinTime:_d_storeResult.beginTime maxTime:_d_storeResult.endTime];
    if (_d_storeResult.planState == kPatrolPlanStatusProcessing) {
        if (_d_storeResult.state == kPatrolStoreStateSubmitted) {
            isNotEdit = YES;
        } else {
            isNotEdit = NO;
        }
    } else {
        isNotEdit = YES;
    }
    
    ICRQuestionManager *mgr = [ICRQuestionManager sharedManager];
    mgr.m_category = displayR.category;//alertInfoPioneering.d_arrCategorys[indexPath.row];
    mgr.m_store_uuid = _d_storeResult.store_uuid;
    mgr.m_plan_uuid = _d_storeResult.plan_uuid;
    [mgr openQuestionVCFromViewControler:self storeResult:_d_storeResult IsNotEdit:isNotEdit ProblemIndex:indexPath.row+1 ];
 
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        return 106;
    } else {
        return 55;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return HEADER_HEIGHT;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    UITableViewHeaderFooterView *headerView = nil;
    if (section >= 2) {
        headerView = [tableView dequeueReusableHeaderFooterViewWithIdentifier:headerItem];
        if (!headerView)
            headerView = [[UITableViewHeaderFooterView alloc] initWithReuseIdentifier:headerItem];
    } else {
        headerView = [tableView dequeueReusableHeaderFooterViewWithIdentifier:headerID];
    }
    CGRect rect = CGRectMake(0, 0, tableView.width, 50);
    [self configureHeaderView:headerView frameWithRect:rect viewForSection:section];
    return headerView;
    
}

- (void)configureHeaderView:(UITableViewHeaderFooterView *)headerView frameWithRect:(CGRect)rect viewForSection:(NSInteger)section {
    UIView *contentView = headerView.contentView;
    
    GTOLicenceResultHeaderContentView *view = [contentView viewWithClass:[GTOLicenceResultHeaderContentView class]];
    if (!view) {
        if (section == 0) {
            view = [[GTOLicenceResultHeaderContentView alloc] initWithFrame:rect isSeePosition:YES];
            [view.m_positionBtn addTarget:self action:@selector(seePositionClicked) forControlEvents:UIControlEventTouchUpInside];
        } else {
            view = [[GTOLicenceResultHeaderContentView alloc] initWithFrame:rect isSeePosition:YES];//[[GTOLicenceResultHeaderContentView alloc] initWithFrame:rect];
        }
        
        [contentView addSubview:view];
    }
    if (section == 0) {
        view.m_positionBtn.hidden = NO;
        [view updateWithString:_d_patrolPlan.name];//@"工程巡检"];
    } else if (section == 1) {
        view.m_positionBtn.hidden = YES;
        [view updateWithString:@"工程巡检结果"];
        
    } else {
        GTOPatrolPlanResultHeaderItem *resultHeader = [contentView viewWithClass:[GTOPatrolPlanResultHeaderItem class]];
        if (!resultHeader) {
            resultHeader = [[GTOPatrolPlanResultHeaderItem alloc] initWithFrame:rect];//
            [contentView addSubview:resultHeader];
        }
        GTODisplayResult *displayR = [GTODisplayResult DBObject];
        [displayR praseFromJsonDict:_d_storeResult.arrDisplayResults[section - 2]];
        resultHeader.isDisplay = displayR.isDisplay;//isDisplay;
        resultHeader.tag = section;
        resultHeader.delegate = self;
        resultHeader.backgroundColor = [UIColor whiteColor];
        [resultHeader updateWithDisplayResult:displayR];
        
        
    }
    
}

- (GTOSubmitPlan *)p_submitPlan {
    //_d_arrDisplayResults
    ICRUserUtil *userU = [ICRUserUtil sharedInstance];
    GTOSubmitPlan *planResult = [GTOSubmitPlan DBObject];
    planResult.uuid = [userU mobileID];
    planResult.user_uuid = _d_storeResult.user_uuid;
    planResult.user_code = _d_storeResult.user_code;
    planResult.user_name = _d_storeResult.user_name;
    planResult.store_uuid = _d_storeResult.store_uuid;
    planResult.store_code = _d_storeResult.store_code;
    planResult.store_name = _d_storeResult.store_name;
    planResult.realStoreUuid = _d_storeResult.realStore_uuid;
    planResult.realStoreCode = _d_storeResult.realStore_code;
    planResult.realStoreName = _d_storeResult.realStore_name;
    planResult.longitude = _d_storeResult.longitude;
    planResult.latitude = _d_storeResult.latitude;
    planResult.beginTime = _d_storeResult.beginTime;
    planResult.endTime = _d_storeResult.endTime;
    planResult.uploadTime = [[NSDate date] httpParameterString];
    planResult.remark = _d_storeResult.remark;
    
    NSMutableArray *muArrAnswers = [@[]mutableCopy];
    for(NSDictionary *dictAnswer in _d_storeResult.answers) {
        ICRAnswer *answer = [ICRAnswer DBObject];
        [answer praseFromJsonDict:dictAnswer];
        GTOSubmitPlanAnswer *submitAnswer = [GTOSubmitPlanAnswer DBObject];
        submitAnswer.uuid = [userU mobileID];
        submitAnswer.questionUuid = answer.questionUuid;
        submitAnswer.score = answer.score;
        submitAnswer.content = answer.content;
        submitAnswer.remark = answer.remark;
        submitAnswer.resultAttachmentId = answer.resultAttachmentId;
        submitAnswer.details = answer.details;
        [muArrAnswers addObject:[submitAnswer dictForCommit]];
    }
    planResult.answers = muArrAnswers;
    return planResult;
}

- (void)p_httpSubmitPatrolResult {
    GTOSubmitPlan *submitPlan  = [self p_submitPlan]; //删除掉服务器上不需要的字段
    ICRHTTPController *httpCtrl = [ICRHTTPController sharedController];
    [IBTLoadingView showProgressLabel:@"正在提交"];
    void (^success)(id data) = ^(id data) {
        CLog(@"%@", data);
        if ([data[@"success"] integerValue] == 1) {
            [IBTLoadingView hideHUDWithText:nil];
            // [self localDelete];
            _d_storeResult.state = kPatrolStoreStateSubmitted;
            //            _d_patrolPlan.finishedStoreNumber =
            [_d_storeResult saveToDBWithHandleData:NULL complete:^{
                [IBTLoadingView hideHUDWithText:nil];
                [self PopViewControllerAnimated:YES];
            } fail:NULL];
            
            return ;
        }  else {
            [IBTLoadingView hideHUDWithText:nil];
            [IBTLoadingView showTextOnly:data[@"message"] inView:self.view];
        }
        
        
    };
    void (^failure)(id) = ^(id data) {
        [IBTLoadingView hideHUDWithText:nil];
        CLog(@"%@", data);
    };
    
    [httpCtrl doSubmitAnswerPatrolPlanWithID:_d_patrolPlan.uuid infoData:[submitPlan dictForCommit] success:success failure:failure];
    
}


#pragma  bottomViewDelegate

- (void)bottomView:(GXFBottomView *)bottomView oneButtonClicked:(UIButton *)oneBtn {
    switch (bottomView.tag) {
        case kBottomViewOneBackTag:
        {
            [self PopViewControllerAnimated:YES];
        }
            break;
        case kBottomViewOneSubmitTag:
        {
            [self upLoadFlieWithAction];
        }
            break;
        default:
            break;
    }
    
}

//上传附件
- (void)upLoadFlieWithAction {
    //有答案的问题的uuid数组
    NSMutableArray *muArr = [@[]mutableCopy];
    NSMutableArray *answerArr = [@[]mutableCopy];
    for (NSDictionary *dictDisplayR in _d_storeResult.arrDisplayResults) {
        GTODisplayResult *displayR = [GTODisplayResult DBObject];
        [displayR praseFromJsonDict:dictDisplayR];
        for (NSDictionary *dictAnswer in displayR.arrAnswers) {
            ICRAnswer *answer = [ICRAnswer DBObject];
            [answer praseFromJsonDict:dictAnswer];
            [answerArr addObject:answer];
            if(answer.questionUuid) [muArr addObject:answer.questionUuid];
        }
        
    }
    
    [IBTLoadingView showProgressLabel:@"上传中"];
    for (int i = 0; i < answerArr.count; i++) {
        ICRAnswer *answer = answerArr[i];
        //找到数据表中的附件
        ICRDatabaseFetchBlock fetchBlk = ^FMResultSet *(FMDatabase *db) {
            NSString *sql = [NSString stringWithFormat:@"SELECT * FROM %@ WHERE %@=? AND %@=? AND %@=? ORDER BY %@",[ICRPostAttachment TableName],@"questionUuid",@"plan_uuid",@"store_uuid",@"addTime"];
            return [db executeQuery:sql,answer.questionUuid,answer.plan_uuid,answer.store_uuid];
        };
        
        __weak typeof(self)weakSelf = self;
        
        ICRDatabaseFetchResultsBlock fetchResultBlk = ^(NSArray *fetchObjects) {
            __strong __typeof(weakSelf)strongSelf = weakSelf;
            if (fetchObjects.count > 0) {
                if (!_d_arrPostAttachments) {
                    strongSelf.d_arrPostAttachments = [@[]mutableCopy];
                } else {
                    [strongSelf.d_arrPostAttachments removeAllObjects];
                }
                [strongSelf.d_arrPostAttachments addObjectsFromArray:fetchObjects];
                CLog(@"开始上传图片%d", i);
                    ICRPostAttachment *postAttachment = fetchObjects[0];
                    ICRHTTPController *httpC = [ICRHTTPController sharedController];
                    [httpC  multiPartUploadWithEntityType:postAttachment.entityType entityUuid:postAttachment.entityUuid arrayPostAttachments:fetchObjects success:^(id data) {
                        if ([data[@"success"] integerValue] == 1) {
                            CLog(@"上传图片%d完成", i);
                            if (i == answerArr.count - 1) {
                                [self p_httpSubmitPatrolResult];
                            }
                            
                        } else {
                            [IBTLoadingView hideHUDWithText:data[@"message"]];
                        }
                    } failure:^(id data) {
                        
                        [IBTLoadingView hideHUDWithText:@"上传失败"];
                    }];                
                
            } else {
                [IBTLoadingView hideHUDWithText:nil];
                [self p_httpSubmitPatrolResult];
            }
        };
        
        ICRDataBaseController *dbCtrl = [ICRDataBaseController sharedController];
        [dbCtrl runFetchForClass:[ICRPostAttachment class]
                      fetchBlock:fetchBlk
               fetchResultsBlock:fetchResultBlk];

    }
    
}

//本地删除
- (void)localDelete {
    //本地删除 许可证
    ICRDataBaseController *dataBaseC = [ICRDataBaseController sharedController];
    [dataBaseC.m_dbQueue inDatabase:^(FMDatabase *db) {
        NSString *strSql = [NSString stringWithFormat:@"DELETE FROM %@ WHERE %@=?",[GTOPatrolPlan TableName],@"uuid" ];
        [db executeUpdate:strSql,_d_patrolPlan.uuid];
    }];
    //删除问题
    [dataBaseC.m_dbQueue inDatabase:^(FMDatabase *db) {
        NSString *strSql = [NSString stringWithFormat:@"DELETE FROM %@ WHERE %@=?",[GTOQuestion TableName],@"patrolPlanUuid" ];
        [db executeUpdate:strSql,_d_patrolPlan.uuid];
    }];
    //删除本地图片
    [dataBaseC.m_dbQueue inDatabase:^(FMDatabase *db) {
        NSString *strSql = [NSString stringWithFormat:@"DELETE FROM %@ WHERE %@=?",[ICRAnswer TableName],@"plan_uuid"];
        [db executeUpdate:strSql,_d_patrolPlan.uuid];
    }];
    
}

- (void)modifyClicked:(UIButton *)btn {
    
}

#pragma GTOPatrolPlanResultHeaderItemDelegate

// 巡检结果中：不同区的headerView点击事件
- (void)patrolPlanResultHeaderItem:(GTOPatrolPlanResultHeaderItem *)resultHeaderItem
                      andIsDisplay:(BOOL)isDisplay {
    NSInteger aIndex = resultHeaderItem.tag - 2;
    
    
    NSMutableArray *muArrDisplayRs = [NSMutableArray array];
    [muArrDisplayRs addObjectsFromArray:_d_storeResult.arrDisplayResults];
    GTODisplayResult *displayR = [GTODisplayResult DBObject];
    [displayR praseFromJsonDict:_d_storeResult.arrDisplayResults[aIndex]];
    displayR.isDisplay = !displayR.isDisplay;
    for (int count = 0; count < _d_storeResult.arrDisplayResults.count; count++) {
        if (count == aIndex) {
            [muArrDisplayRs replaceObjectAtIndex:aIndex withObject:[displayR dictForCommit]];
            break;
        }
        
    }
    
    
    _d_storeResult.arrDisplayResults = muArrDisplayRs;
    
    //    [_d_storeResult saveToDBWithHandleData:NULL complete:^{
    //        [_c_tableView reloadData];
    //    } fail:NULL];
    
    [_c_tableView reloadData];
    //   [_d_storeResult saveToDBWithHandleData:NULL complete:^{
    //       [_c_tableView reloadData];
    //   }                             fail:nil];
    
}
- (void)seePositionClicked {
    GTOPositionMapViewController *mapVC = [[GTOPositionMapViewController alloc]initWithStoreResult:_d_storeResult];
    [self PushViewController:mapVC animated:YES];
}
@end
