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

#import "GTOQResultViewController.h"
#import "ICRQuestionHelperView.h"
#import "ICRAttachmentView.h"

#import "GTOPioneering.h"

#import "GTODisplayResult.h"
#import "GTOQuestion.h"
#import "GTOAnswer.h"


#import "GTOPatrolPlanResultHeaderItem.h"
#import "GTOPatrolPlanResultProblemItem.h"
#import "GTOPatrolPlanResultTopItem.h"

#import "GTOPioneeringListViewController.h"
#import "GTOPioneeringSurveyItem.h"
#import "GTOPioneeringResult.h"
#import "GTOEditPioneeringViewController.h"
#import "GXFBottomView.h"
#import "GTOQuestionBaseViewController.h"
#import "GTOPioneeringAddressInfoViewController.h"
#import "ICRPostAttachment.h"
#import "GTOQuestionManager.h"
#define GXF_DETAIL_COLOR        HexColor(@"888888")
#define GXF_CONTENT_COLOR       HexColor(@"444444")

#define KEY_IS_DISPLAY @"isDisplay"
static  NSString *cellTopID = @"topCellID";
static  NSString *cellQuestionID = @"questionCellID";
static  NSString *headerBtnID = @"headerBtnID";
static  NSString *headerTitleID = @"headerTitleID";
static  NSString *headerCategoryID = @"headerCategoryID";
typedef NS_ENUM(NSUInteger, bottomViewTag) {
    
    kBottomViewTwoSaveSubmittedTag = 0,
    // kBottomViewTwoBackSaveTag,
    kBottomViewOneBackTag,
};
@interface GTOQResultViewController ()
<UITextFieldDelegate,
UITableViewDataSource,
UITableViewDelegate,
GTOPatrolPlanResultHeaderItemDelegate,
GXFBottomViewDelegate,
UIAlertViewDelegate>


@property (strong, nonatomic) ICRQuestionHelperView *m_helperView;


@property (nonatomic, strong) NSIndexPath *m_clickedIndexPath;

/////
@property (strong, nonatomic) GTOPioneering *d_pioneering;

@property (nonatomic, strong) UITableView *c_tableView;
//@property (nonatomic, strong) NSArray *d_arrCategorys; //问题按区域分
//@property (nonatomic, assign) BOOL d_isAllfinished;//所有问题没有回答完
@property (nonatomic, strong) NSMutableArray *d_arrPostAttachments;
@property (nonatomic, strong) NSIndexPath *d_indexPath;
//@property (nonatomic, assign) NSUInteger d_totalPhotos;//某一任务中的图片操作的个数
//@property (nonatomic, assign) NSUInteger d_calculateTotalPhotos;
@end

@implementation GTOQResultViewController

#pragma mark - Life Cycle
- (instancetype)initWithPioneering:(GTOPioneering *)pioneering  {
    self = [super init];
    if (!self) {
        return nil;
    }
    
    if ([pioneering isKindOfClass:[GTOPioneering class]]) {
        self.d_pioneering = pioneering;
        //[self p_problemsCategory];
    }
    
    
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    UIBarButtonItem *backItem = [[UIBarButtonItem alloc]init];
    backItem.title = @"";
    self.navigationItem.backBarButtonItem = backItem;
    
    self.title = @"拓站结果";
    
    
    [self initSubViews];
    
}
- (void)viewWillAppear:(BOOL)animated {
    [self updateAnsewer];
    //        [self.c_tableView reloadData];
}
- (void)updateAnsewer {
    ICRDatabaseFetchBlock fetchBlk = ^FMResultSet *(FMDatabase *db) {
        NSString * sql = [NSString stringWithFormat:@"SELECT *  FROM %@ WHERE %@ = ? ORDER BY %@", [GTOAnswer TableName], @"pioneeringUuid",@"questionUuid"];
        //答案的排序按照问题的uuid来，（此事的排序关系到结果页中答案的显示，按道理应该是根据答题的顺序，是不是后台给的问题应该排序？？？？？）
        NSLog(@"%@",sql);
        return [db executeQuery:sql,_d_pioneering.uuid];
    };
    
    __weak typeof(self)weakSelf = self;
    ICRDatabaseFetchResultsBlock fetchResultsBlk = ^(NSArray *fetchedObjects) {
        __strong __typeof(weakSelf)strongSelf = weakSelf;
        
        NSMutableArray *muArrDisplayRs = [NSMutableArray array];
        for (int count = 0; count < _d_pioneering.arrDisplayResults.count; count ++) {
            // NSInteger finiseNumber = 0;
            GTODisplayResult *displayR = [GTODisplayResult DBObject];
            [displayR praseFromJsonDict:_d_pioneering.arrDisplayResults[count]];
            //displayR.answerNumber = 0;
            NSMutableArray *muArrAnswers = [NSMutableArray array];
            for (GTOAnswer *answer in fetchedObjects) {
                if([answer.category isEqualToString:displayR.category])
                    //displayR.answerNumber++;
                    [muArrAnswers addObject:[answer dictForCommit]];
            }
            displayR.arrAnswers = muArrAnswers;
            
            [muArrDisplayRs addObject:[displayR dictForCommit]];
        }
        _d_pioneering.arrDisplayResults = muArrDisplayRs;
        [_d_pioneering saveToDBWithHandleData:nil complete:^{
            
            [_c_tableView reloadData];
        } fail:nil];
        
    };
    
    ICRDataBaseController *dbCtrl = [ICRDataBaseController sharedController];
    [dbCtrl runFetchForClass:[GTOAnswer 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:cellQuestionID];
    [self.c_tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:cellTopID];
    [self.c_tableView registerClass:[UITableViewHeaderFooterView class] forHeaderFooterViewReuseIdentifier:headerBtnID];
    [self.c_tableView registerClass:[UITableViewHeaderFooterView class] forHeaderFooterViewReuseIdentifier:headerTitleID];
    [self.c_tableView registerClass:[UITableViewHeaderFooterView class] forHeaderFooterViewReuseIdentifier:headerCategoryID];
    [self.view addSubview:_c_tableView];
    
    //bottomView
    
    CGRect rect = CGRectMake(0, _c_tableView.bottom, self.view.width, 40) ;
    GXFBottomView *bottomV;
    if ([_d_pioneering.state isEqualToString:GTO_PIONEERING_STATE_INITIAL]
        || [_d_pioneering.state isEqualToString:GTO_PIONEERING_STATE_LOCAL]) {
        
        bottomV = [[GXFBottomView alloc]initWithFrame:CGRectMake(0, _c_tableView.bottom, self.view.width, 40) leftButtonColor:GTO_RED_COLOR rightButtonColor:GTO_BLUE_DEEP_COLOR LeftBtnTitle:@""rightBtnTitle:@""];
        NSUInteger noFinishNumber = 0;
        for(NSDictionary *dictDisplayR in _d_pioneering.arrDisplayResults) {
            GTODisplayResult *displayR = [GTODisplayResult DBObject];
            [displayR praseFromJsonDict:dictDisplayR];
            if(displayR.arrAnswers.count != displayR.arrQuestions.count)
                noFinishNumber ++;
        }
        if (noFinishNumber > 0) {
            //            bottomV.tag = kBottomViewTwoBackSaveTag;
            //
            //            [bottomV.f_leftBtn setTitle:@"返回" forState:UIControlStateNormal];
            //            [bottomV.f_rightBtn setTitle:@"保存" forState:UIControlStateNormal];
            bottomV = [[GXFBottomView alloc]initOneButtonWithFrame:rect buttonColor:GTO_RED_COLOR buttonTitle:@"返回"];
            bottomV.tag = kBottomViewOneBackTag;
            
        } else {
            bottomV.tag = kBottomViewTwoSaveSubmittedTag;
            [bottomV.f_leftBtn setTitle:@"保存" forState:UIControlStateNormal];
            [bottomV.f_rightBtn setTitle:@"提交" forState:UIControlStateNormal];
            
        }
    } else {
        
        bottomV = [[GXFBottomView alloc]initOneButtonWithFrame:rect buttonColor:GTO_BLUE_DEEP_COLOR buttonTitle:@"返 回"];
        bottomV.tag = kBottomViewOneBackTag;
        
    }
    bottomV.backgroundColor = XXFBgColor;
    bottomV.delegate = self;
    
    [self.view addSubview:bottomV];
}



#pragma UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 2 +  _d_pioneering.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_pioneering.arrDisplayResults.count; count ++) {  //
            if (section == count + 2) {
                GTODisplayResult *displayR = [GTODisplayResult DBObject];
                [displayR praseFromJsonDict:_d_pioneering.arrDisplayResults[count]];
                //                return   displayR.isDisplay ? displayR.arrAnswers.count : 0;
                return   displayR.isDisplay ? displayR.arrQuestions.count : 0;
                
            }
        }
        
        return 0;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell;
    if (indexPath.section == 0) {
        cell = [tableView dequeueReusableCellWithIdentifier:cellTopID forIndexPath:indexPath];
    } else {
        cell = [tableView dequeueReusableCellWithIdentifier:cellQuestionID forIndexPath:indexPath];
    }
    
    [self configureCellWithTableViewCell:cell cellForRowAtIndexPath:indexPath];
    
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    return cell;
}
- (void)configureCellWithTableViewCell: (UITableViewCell *)cell
                 cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UIView *contentView = cell.contentView;
    CGRect rect = CGRectMake(0, 0, self.view.width, contentView.height);
    if (indexPath.section == 0) {
        
        GTOPatrolPlanResultTopItem *topItem = [contentView viewWithClass:[GTOPatrolPlanResultTopItem class]];
        if (!topItem) {
            topItem = [[GTOPatrolPlanResultTopItem alloc]initWithFrame:rect];
            [contentView addSubview:topItem];
        }
        [topItem updateWithPioneering:_d_pioneering arrayDictDisplayResults:_d_pioneering.arrDisplayResults];
    } else if(indexPath.section > 1){
        GTOPatrolPlanResultProblemItem *problemItem = [contentView viewWithClass:[GTOPatrolPlanResultProblemItem class]];
        if (!problemItem) {
            problemItem = [[GTOPatrolPlanResultProblemItem alloc]initWithFrame:rect];
            problemItem.m_modifyBtn.tag = indexPath.row;
            [problemItem.m_modifyBtn addTarget:self action:@selector(modifyClicked:) forControlEvents:UIControlEventTouchUpInside];
            
            [contentView addSubview:problemItem];
        }
        GTODisplayResult *displayR = [GTODisplayResult DBObject];
        [displayR praseFromJsonDict:_d_pioneering.arrDisplayResults[indexPath.section - 2]];
        GTOQuestion *question = [GTOQuestion DBObject];
        [question praseFromJsonDict:displayR.arrQuestions[indexPath.row]];
        //        BOOL is_answered = NO;
        //        GTOAnswer *findaAnswer ;//= [GTOAnswer DBObject];
        //        for(NSDictionary *dict in displayR.arrAnswers){
        //            GTOAnswer *answer = [GTOAnswer DBObject];
        //            [answer praseFromJsonDict:dict];
        //            if ([answer.questionUuid isEqualToString:question.uuid]) {
        ////                is_answered = YES;
        //                findaAnswer = answer;
        //                break;
        //            }
        //        }
        
        [self uploadePatrolPlanResultProblemItemAnswer:problemItem question:question cellForRowAtIndexPath:indexPath];
        //        GTOAnswer *answer = [GTOAnswer 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]) {
        ////                [self uploadePatrolPlanResultProblemItemAnswer:problemItem question:question cellForRowAtIndexPath:indexPath];
        //                      [problemItem updateWithQuestion:question answer:answer index:indexPath.row];
        //            }
        //
        //        }
        
    } else {
        
    }
}
- (void)uploadePatrolPlanResultProblemItemAnswer: (GTOPatrolPlanResultProblemItem *)problemItem question: (GTOQuestion *)question cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    ICRDatabaseFetchBlock fetchBlk = ^FMResultSet *(FMDatabase *db) {
        NSString * sql = [NSString stringWithFormat:@"SELECT *  FROM %@ WHERE %@ = ? AND %@ = ? AND %@ = ?", [GTOAnswer TableName], @"pioneeringUuid",@"questionUuid",@"category" ];
        //答案的排序按照问题的uuid来，（此事的排序关系到结果页中答案的显示，按道理应该是根据答题的顺序，是不是后台给的问题应该排序？？？？？）
        NSLog(@"%@",sql);
        return [db executeQuery:sql,_d_pioneering.uuid,question.uuid,question.category];
    };
    
    __weak typeof(self)weakSelf = self;
    ICRDatabaseFetchResultsBlock fetchResultsBlk = ^(NSArray *fetchedObjects) {
        __strong __typeof(weakSelf)strongSelf = weakSelf;
        if (fetchedObjects) {
            GTOAnswer *answer = fetchedObjects[0];
            [problemItem updateWithQuestion:question answer:answer index:indexPath.row];
        } else {
            [problemItem updateWithQuestion:question answer:nil index:indexPath.row];
        }
        
    };
    ICRDataBaseController *dbCtrl = [ICRDataBaseController sharedController];
    [dbCtrl runFetchForClass:[GTOAnswer class]
                  fetchBlock:fetchBlk
           fetchResultsBlock:fetchResultsBlk];
}
#pragma UITableViewDelegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section < 2)
    { return;
    }
    
    GTODisplayResult *displayR = [GTODisplayResult DBObject];
    [displayR praseFromJsonDict:_d_pioneering.arrDisplayResults[indexPath.section - 2]];
    GTOQuestion *question = [GTOQuestion DBObject];
    [question praseFromJsonDict:displayR.arrQuestions[indexPath.row]];
    GTOQuestionManager *mgr = [GTOQuestionManager sharedManager];
    mgr.d_category = question.category;
    
    BOOL notEdit = NO;
    if ([_d_pioneering.state isEqualToString:GTO_PIONEERING_STATE_SUBMITTED]) {
        notEdit = YES;
    } else {
        notEdit = NO;
    }
    [mgr openQuestionVCFromViewControler:self Licence:nil Pioneering:_d_pioneering IsNotEdit:notEdit ProblemIndex:indexPath.row + 1];
    
    //    if ([_d_pioneering.state isEqualToString:GTO_PIONEERING_STATE_LOCAL] &&
    //        (displayR.arrQuestions.count != displayR.arrAnswers.count)) {
    //        [mgr openQuestionVCFromViewControler:self withPioneering:_d_pioneering];
    //    }else {
    //        [mgr openQuestionVCFromViewControler:self Licence:nil Pioneering:_d_pioneering IsNotEdit:notEdit ProblemIndex:indexPath.row + 1];
    //    }
    
    
    //    GTOAnswer *answer = [GTOAnswer 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]) {
    //            BOOL notEdit = NO;
    //            if ([_d_pioneering.state isEqualToString:GTO_PIONEERING_STATE_SUBMITTED]) {
    //                notEdit = YES;
    //            } else {
    //                notEdit = NO;
    //            }
    //             GTOQuestionManager *mgr = [GTOQuestionManager sharedManager];
    //             mgr.d_category = question.category;
    //            [mgr openQuestionVCFromViewControler:self Licence:nil Pioneering:_d_pioneering IsNotEdit:notEdit ProblemIndex:indexPath.row + 1];
    //            break;
    //        }
    //
    //    }
    
    self.d_indexPath = indexPath;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        return 126;
    } else {
        return 55;
    }
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return HEADER_HEIGHT;
}
- (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];
        view.backgroundColor = [UIColor yellowColor];
        if (!view) {
            view = [[UIView alloc]initWithFrame:rect];//tableView.tableHeaderView.bounds];
            CGRect rect = CGRectMake(padding, 0, 150, view.height);
            UIFont *font = [UIFont systemFontOfSize:18];
            IBTUILabel *lblTitle = [[IBTUILabel alloc]initWithFrame:rect text:_d_pioneering.title font:font tintColor:[UIColor blackColor] backgroundColor:XXFBgColor textAlignment:NSTextAlignmentLeft];
            
            //            rect = CGRectMake( view.width - 10 - 100, 0, 100, lblTitle.height);//
            //            UILabel *lblAddress = [[IBTUILabel alloc]initWithFrame:rect text:@"查看位置" font:font tintColor:[UIColor blackColor] backgroundColor:XXFBgColor textAlignment:NSTextAlignmentLeft];
            
            
            CGFloat signBtnW = 120;
            UIButton *signBtn = [[UIButton alloc]initWithFrame:CGRectMake(view.width - 10 - 150, 0, 150, lblTitle.height)];
            signBtn.titleLabel.font = [UIFont systemFontOfSize:20];
            [signBtn.titleLabel setTextAlignment:NSTextAlignmentRight];
            [signBtn setTitle:@"查看位置" forState:UIControlStateNormal];
            [signBtn setTitleColor:GTO_BLUE_TINT_COLOR forState:UIControlStateNormal];
            // [signBtn setImage:[UIImage imageNamed:@"icon_nav_start"] forState:UIControlStateNormal];
            [signBtn addTarget:self action:@selector(seeAddressClicked) forControlEvents:UIControlEventTouchUpInside];
            [self.view addSubview:signBtn];
            
            [view addSubview:lblTitle];
            [view addSubview:signBtn];
            
            view.backgroundColor = XXFBgColor;
        }
    } else if (section == 1) {
        headerID = @"stateID";
        UIFont *font = [UIFont systemFontOfSize:18];
        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:font tintColor:[UIColor blackColor] backgroundColor:XXFBgColor textAlignment:NSTextAlignmentLeft];
            
            
            [view addSubview:lblState];
        }
        view.backgroundColor = XXFBgColor;
    } else {
        headerID = @"categoryID";
        view =[tableView dequeueReusableHeaderFooterViewWithIdentifier:headerID];
        
        if (!view) {
            GTOPatrolPlanResultHeaderItem *resultHeader = (GTOPatrolPlanResultHeaderItem *)[[GTOPatrolPlanResultHeaderItem alloc]initWithFrame:rect];//
            // GTODisplayResult *displayR = _d_arrDisplayResults[section - 2];
            GTODisplayResult *displayR = [GTODisplayResult DBObject];
            [displayR praseFromJsonDict:_d_pioneering.arrDisplayResults[section - 2]];
            resultHeader.isDisplay = displayR.isDisplay;//isDisplay;
            
            resultHeader.delegate = self;
            resultHeader.backgroundColor = [UIColor whiteColor];
            [resultHeader updateWithDisplayResult:displayR];
            resultHeader.tag = section ;
            view = resultHeader;
        }
        
    }
    
    return view;
    
}
- (GTOPioneeringResult *)p_pioneeringResult {
    //_d_arrDisplayResults
    NSMutableArray *muArrItems = [NSMutableArray array];
    for(NSDictionary *dictDisplayR in _d_pioneering.arrDisplayResults ){
        GTODisplayResult *displayR = [GTODisplayResult DBObject];
        [displayR praseFromJsonDict:dictDisplayR];
        //        for(NSDictionary *dictAnswer in displayR.arrAnswers){ //一条数据
        //            GTOAnswer *answer = [GTOAnswer DBObject];
        //            [answer praseFromJsonDict:dictAnswer];
        //            GTOPioneeringSurveyItem *surveyItem = [[GTOPioneeringSurveyItem alloc]init];
        //            NSMutableDictionary *muDictItem = [NSMutableDictionary dictionary];
        //            GTOQuestion *ques;  //找到答案对应的question
        //            for(NSDictionary *dictQuestion in displayR.arrQuestions){
        //                GTOQuestion *question = [GTOQuestion DBObject];
        //                [question praseFromJsonDict:dictQuestion];
        //                if ([question.uuid isEqualToString:answer.questionUuid]) {
        //                    ques = question;
        //                    break;
        //                }
        //            }
        
        for(NSDictionary *dictQuestion in displayR.arrQuestions){ //一条数据
            GTOQuestion *question = [GTOQuestion DBObject];
            [question praseFromJsonDict:dictQuestion];
            GTOPioneeringSurveyItem *surveyItem = [[GTOPioneeringSurveyItem alloc]init];
            NSMutableDictionary *muDictItem = [NSMutableDictionary dictionary];
            GTOAnswer *ans;  //找到问题对应的answer
            for(NSDictionary *dictAnswer in displayR.arrAnswers){
                GTOAnswer *answer = [GTOAnswer DBObject];
                [answer praseFromJsonDict:dictAnswer];
                if ([question.uuid isEqualToString:answer.questionUuid]) {
                    ans = answer;
                    break;
                }
            }
            surveyItem.uuid = question.uuid;//用答案的uuid去标识每个问题的uuid
            
            surveyItem.details = question.details;
            surveyItem.resultDetails = ans.resultDetails;
            
            
            surveyItem.category = question.category;
            surveyItem.type = question.type;
            surveyItem.lineNo = question.lineNo;
            surveyItem.reference = question.reference;
            surveyItem.attachmentId = question.attachmentId;
            surveyItem.title = question.title;
            surveyItem.star = question.star;
            surveyItem.scoreFrom = question.scoreFrom;
            surveyItem.scoreTo = question.scoreTo;
            surveyItem.writingReply = question.writingReply;
            surveyItem.pictureReply = question.pictureReply;
            surveyItem.recordReply = question.recordReply;
            
            if(ans) {
                surveyItem.resultScore = ans.resultScore;
                surveyItem.resultContent = ans.resultContent;
                surveyItem.resultRemark = ans.resultRemark;
                surveyItem.resultAttachmentId = ans.resultAttachmentId;
            }
            
            [muArrItems addObject:[surveyItem dictForCommit]];
        }
    }
    
    GTOPioneeringResult *result = [[GTOPioneeringResult alloc]init];
    result.uuid = _d_pioneering.uuid;
    result.version = _d_pioneering.version;
    result.title = _d_pioneering.title;
    result.pioneer_uuid = _d_pioneering.pioneer_uuid;
    result.pioneer_code = _d_pioneering.pioneer_code;
    result.pioneer_name = _d_pioneering.pioneer_name;
    result.templateName = _d_pioneering.templateName;
    result.beginDate =  [[NSDate date] httpParameterString];//_d_pioneering.beginDate;
    result.remark = _d_pioneering.remark;
    result.longitude = _d_pioneering.longitude;
    result.latitude = _d_pioneering.latitude;
    result.items = muArrItems;
    
    
    return result;
}
- (void)httpSubmitPioneeringResult {
    NSDate *date = [NSDate date];
    GTOPioneeringResult *pioneeringR = [self p_pioneeringResult];
    ICRHTTPController *httpCtrl = [ICRHTTPController sharedController];
    
    [IBTLoadingView showProgressLabel:@"正在提交"];
    // [IBTLoadingView hideHUDWithText:nil];
    void (^success)(id data) = ^(id data) {
//        CLog(@"%@", data);
        [IBTLoadingView hideHUDWithText:nil];
        if ([data[@"success"] integerValue] == 1) {
            [IBTLoadingView hideHUDWithText:nil];
            [self localDelete];
            if ([_d_pioneering.state isEqualToString:GTO_PIONEERING_STATE_LOCAL] ) {
                [self PopToViewControllerAtIndex:1 animated:YES];
            } else {
                [self PopViewControllerAnimated:YES];
            }
            
        } else {
            [IBTLoadingView showTextOnly:data[@"message"] inView:self.view];
        }
        //        _d_pioneering.state = GTO_PIONEERING_STATE_SUBMITTED;
        //        [_d_pioneering saveToDBWithHandleData:NULL
        //                                     complete:^{
        //
        //                                     }
        //                                         fail:^(NSError *error) {
        //
        //                                             [IBTLoadingView hideHUDWithText:error.localizedDescription];
        //                                         }];
    };
    void (^failure)(id ) = ^(id data) {
        [IBTLoadingView showTextOnly:@"提交失败" inView:self.view];
//        CLog(@"%@", data);
    };
    
    
    [httpCtrl doSubmitPioneeringResultWithData:[pioneeringR dictForCommit] success:success failure:failure];
    
    
}
- (void)httpSavePioneeringResult {
    //[self upLoadFlie];
    NSDate *date = [NSDate date];
    GTOPioneeringResult *pioneeringR = [self p_pioneeringResult];
    
    
    [IBTLoadingView showProgressLabel:@"正在保存"];
    // [IBTLoadingView hideHUDWithText:nil];
    void (^success)(id data) = ^(id data) {
//        CLog(@"%@", data);
        
        if ([data[@"success"] integerValue] == 1) {
            [IBTLoadingView hideHUDWithText:nil];
            [self localDelete];
            
            if ([_d_pioneering.state isEqualToString:GTO_PIONEERING_STATE_LOCAL] ) {
                [self PopToViewControllerAtIndex:1 animated:YES];
            } else {
                [self PopViewControllerAnimated:YES];
            }
            //            GTOPioneeringListViewController *pioneeringListVC = [[GTOPioneeringListViewController alloc]init];
            //            [self PushViewController:pioneeringListVC animated:YES];
            //            [self PresentModalViewController:pioneeringListVC animated:YES];
        } else {
            [IBTLoadingView showTextOnly:data[@"message"] inView:self.view];
        }
        
        
    };
    void (^failure)(id ) = ^(id data) {
        [IBTLoadingView showTextOnly:@"保存失败" inView:self.view];
//        CLog(@"%@", data);
    };
    
    ICRHTTPController *httpCtrl = [ICRHTTPController sharedController];
    [httpCtrl doSavePioneeringResultWithData:[pioneeringR dictForCommit] success:success failure:failure];
    
    //    //本地删除
    //    ICRDataBaseController *dataBaseC = [ICRDataBaseController sharedController];
    //    [dataBaseC.m_dbQueue inDatabase:^(FMDatabase *db) {
    //        NSString *strSql = [NSString stringWithFormat:@"DELETE FROM %@ WHERE %@=?",[GTOPioneering TableName],@"uuid" ];
    //        [db executeUpdate:strSql,_d_pioneering.uuid];
    //    }];
    
    
}
- (void)getTotalPhotosInTaskWithAction: (NSString *)action {
    ICRDatabaseFetchBlock fetchBlk = ^FMResultSet *(FMDatabase *db) {
        NSString *sql = [NSString stringWithFormat:@"SELECT * FROM %@ WHERE %@=? ORDER BY %@",[ICRPostAttachment TableName],@"pioneeringUuid",@"addTime"];
        return [db executeQuery:sql,_d_pioneering.uuid];
    };
    
    __weak typeof(self)weakSelf = self;
    ICRDatabaseFetchResultsBlock fetchResultBlk = ^(NSArray *fetchObjects) {
        __strong __typeof(weakSelf)strongSelf = weakSelf;
        
        if (fetchObjects.count <= 0) {
            if ([action isEqualToString:@"save"]) {
                [self httpSavePioneeringResult];
            } else {
                [self httpSubmitPioneeringResult];
            }
            return ;
        } else {
            NSMutableArray *arr = [@[]mutableCopy];
            for(ICRPostAttachment *postAttachment in fetchObjects){
                if (postAttachment.is_delete || postAttachment.is_localPhoto) {
                    [arr addObject:postAttachment];
                }
            }
            //            strongSelf.d_totalPhotos = arr.count;
            [strongSelf upLoadFlieWithAction:action];
        }
        
    };
    
    ICRDataBaseController *dbCtrl = [ICRDataBaseController sharedController];
    [dbCtrl runFetchForClass:[ICRPostAttachment class]
                  fetchBlock:fetchBlk
           fetchResultsBlock:fetchResultBlk];
}
//上传附件
- (void)upLoadFlieWithAction: (NSString *)action {
    
    for (int count = 0; count < _d_pioneering.arrDisplayResults.count; count ++) {
        GTODisplayResult *displayR = [GTODisplayResult DBObject];
        [displayR praseFromJsonDict:_d_pioneering.arrDisplayResults[count]];
        for (int ansCount = 0; ansCount < displayR.arrAnswers.count; ansCount ++) {
//            if(count ==0 && ansCount==0){
//                [IBTLoadingView showProgressLabel:@"正在上传图片"];
//            }
            GTOAnswer *answer = [GTOAnswer DBObject];
            [answer praseFromJsonDict:displayR.arrAnswers[ansCount]];
            BOOL isFinish = NO;
            if ((ansCount == displayR.arrAnswers.count - 1)
                && (count == _d_pioneering.arrDisplayResults.count - 1)) {
                isFinish = YES;
            }
            [self everyProblemUpLoadPhotoWithAnswer:answer isFinishedUpload:isFinish action:action];
            //            if (count == _d_pioneering.arrDisplayResults.count - 1) {
            //                if (ansCount == displayR.arrAnswers.count - 1) {
            //                    [self everyProblemUpLoadPhotoWithAnswer:answer isFinishedUpload:YES action:action];
            //                }
            //            }
        }
    }
    
}

- (void)everyProblemUpLoadPhotoWithAnswer: (GTOAnswer *)answer
                         isFinishedUpload: (BOOL)isFinish
                                   action: (NSString *)action{
    //找到数据表中的附件
    
    ICRDatabaseFetchBlock fetchBlk = ^FMResultSet *(FMDatabase *db) {
        NSString *sql = [NSString stringWithFormat:@"SELECT * FROM %@ WHERE %@=? AND %@=? ORDER BY %@",[ICRPostAttachment TableName],@"questionUuid",@"pioneeringUuid",@"addTime"];
        return [db executeQuery:sql,answer.questionUuid,answer.pioneeringUuid];
    };
    
    __weak typeof(self)weakSelf = self;
    ICRDatabaseFetchResultsBlock fetchResultBlk = ^(NSArray *fetchObjects) {
        __strong __typeof(weakSelf)strongSelf = weakSelf;
        if (!fetchObjects) {
            if (!isFinish) {
                return ;
            } else {
                if ([action isEqualToString:@"save"]) {
                    [self httpSavePioneeringResult];
                } else {
                    [self httpSubmitPioneeringResult];
                }
                return;
            }
        }
        if (fetchObjects.count > 0) {
            
            if (!_d_arrPostAttachments) {
                strongSelf.d_arrPostAttachments = [@[]mutableCopy];
            } else {
                [strongSelf.d_arrPostAttachments removeAllObjects];
            }
            
            //            [strongSelf.d_arrPostAttachments addObjectsFromArray:fetchObjects];
            
            NSMutableArray *delArr = [@[]mutableCopy];
            NSMutableArray *delArrPostAttachments = [@[]mutableCopy];
            NSMutableArray *addArrPostAttachments = [@[]mutableCopy];
            for(ICRPostAttachment *postAttachment in fetchObjects) {
                if (postAttachment.is_delete) {
                    [delArr addObject:postAttachment.uuid];
                }
                if (postAttachment.is_localPhoto) {
                    [addArrPostAttachments addObject:postAttachment];
                    [strongSelf.d_arrPostAttachments addObject:postAttachment];
                } else if (!postAttachment.is_localPhoto && postAttachment.is_delete) {
                    [delArrPostAttachments addObject:postAttachment];
                    [strongSelf.d_arrPostAttachments addObject:postAttachment];
                } else{}
            }
            NSString *delStr = [delArr componentsJoinedByString:@";"];
            if (delStr.length <= 0) {
                delStr = @"";
            }
            //            if(_d_arrPostAttachments.count > 0) {
            if(addArrPostAttachments.count > 0 || delArrPostAttachments.count > 0) {
                ICRPostAttachment *postAttachment = _d_arrPostAttachments[0];
                void(^succAdd)(id) = ^(id data) {
                    if ([data[@"success"] integerValue] == 1) {
                        
                        [strongSelf localDeleteOneAnswerPhotos:answer];
                        //                        strongSelf.d_calculateTotalPhotos ++;
                        if (!isFinish) {
                            return ;
                        } else {
                            [IBTLoadingView hideHUDWithText:nil];
                            if ([action isEqualToString:@"save"]) {
                                [self httpSavePioneeringResult];
                            } else {
                                [self httpSubmitPioneeringResult];
                            }
                        }
                        
                        
                    } else {
                        [IBTLoadingView hideHUDWithText:data[@"message"]];
                    }
                };
                
                void(^failAdd)(id) = ^(id data) {
                    [IBTLoadingView hideHUDWithText:@"上传图片出错啦！ 请重新上传。"];
                };
                
                void(^succDel)(id) = ^(id data) {
                    if ([data[@"success"] integerValue] == 1) {
                        
                        [strongSelf localDeleteOneAnswerPhotos:answer];
                        //                        strongSelf.d_calculateTotalPhotos ++;
                        //                        if (_d_calculateTotalPhotos < _d_totalPhotos) {
                        if (!isFinish) {
                            return ;
                        } else {
                            [IBTLoadingView hideHUDWithText:nil];
                            if ([action isEqualToString:@"save"]) {
                                [self httpSavePioneeringResult];
                            } else {
                                [self httpSubmitPioneeringResult];
                            }
                        }
                        
                    } else {
                        [IBTLoadingView hideHUDWithText:data[@"message"]];
                    }
                };
                
                void(^failDel)(id) = ^(id data) {
                    [IBTLoadingView hideHUDWithText:@"上传删除的图片出错啦！ 请重新上传。"];
                };
                
                
                ICRHTTPController *httpC = [ICRHTTPController sharedController];
                if (delArrPostAttachments.count >0) {
                    
                    [httpC deleteAttachments:delStr success:succDel failure:failDel];
                }
                if (addArrPostAttachments.count >0) {
                    [httpC  multiPartUploadWithEntityType:postAttachment.entityType entityUuid:postAttachment.entityUuid arrayPostAttachments:addArrPostAttachments success:succAdd failure:failAdd];
                }
                
            }else {
                if (!isFinish) {
                    return ;
                } else {
                    if ([action isEqualToString:@"save"]) {
                        [self httpSavePioneeringResult];
                    } else {
                        [self httpSubmitPioneeringResult];
                    }
                }
                
            }
        }
    };
    
    ICRDataBaseController *dbCtrl = [ICRDataBaseController sharedController];
    [dbCtrl runFetchForClass:[ICRPostAttachment class]
                  fetchBlock:fetchBlk
           fetchResultsBlock:fetchResultBlk];
}
////上传附件
//- (void)upLoadFlieWithAction: (NSString *)action {
//
//
//    //有答案的问题的uuid数组
//    NSMutableArray *muArr = [@[]mutableCopy];
//    for (NSDictionary *dictDisplayR in _d_pioneering.arrDisplayResults) {
//        GTODisplayResult *displayR = [GTODisplayResult DBObject];
//        [displayR praseFromJsonDict:dictDisplayR];
//        for (NSDictionary *dictAnswer in displayR.arrAnswers) {
//            GTOAnswer *answer = [GTOAnswer DBObject];
//            [answer praseFromJsonDict:dictAnswer];
//            if(answer.questionUuid) [muArr addObject:answer.questionUuid];
//
//        }
//
//    }
//    //找到数据表中的附件
//
//    ICRDatabaseFetchBlock fetchBlk = ^FMResultSet *(FMDatabase *db) {
//        NSString *sql = [NSString stringWithFormat:@"SELECT *FROM %@ WHERE %@ IN %@ ORDER BY %@ ",[ICRPostAttachment TableName],@"questionUuid",[IBTModel ValuePlaceholdersWithCount:muArr.count],@"addTime"];
//        return [db  executeQuery:sql withArgumentsInArray:muArr];
//    };
//
//    __weak typeof(self)weakSelf = self;
//    ICRDatabaseFetchResultsBlock fetchResultBlk = ^(NSArray *fetchObjects) {
//        __strong __typeof(weakSelf)strongSelf = weakSelf;
//        if (fetchObjects.count > 0) {
//
//
//                for (int i = 0; i < _d_arrPostAttachments.count; i++) {
//                    ICRPostAttachment *postAttachment = _d_arrPostAttachments[i];
//                    void(^succ)(id) = ^(id data) {
//
//                        if ([data[@"success"] integerValue] == 1) {
//                            if (i == _d_arrPostAttachments.count - 1) {
//                                [IBTLoadingView hideHUDWithText:nil];
//                                if ([action isEqualToString:@"save"]) {
//                                    [self httpSavePioneeringResult];
//                                } else {
//                                    [self httpSubmitPioneeringResult];
//                                }
//
//                            }
//
//
//                        } else {
//
//                            [IBTLoadingView hideHUDWithText:data[@"message"]];
//                        }
//
//                    };
//                    void(^fail)(id) = ^(id data) {
//                        [IBTLoadingView hideHUDWithText:@"这张图片上传失败"];
//
//                    };
//
//                    if (i == 0) {
//                        [IBTLoadingView showProgressLabel:@"正在上传图片"];
//                    }
//                    NSData *data = [NSData dataWithContentsOfFile:postAttachment.filePath];
//                    NSString *baseStr = [data base64EncodedString];
//                    NSDictionary *dictPar = @{@"fileName":postAttachment.fileName,@"entityType":postAttachment.entityType,@"entityUuid":postAttachment.entityUuid,@"content":baseStr};
//                    ICRHTTPController *httpC = [ICRHTTPController sharedController];
//                    [httpC doAttachmentUploadWithData:dictPar success:succ failure:fail];
//                  //                }
//            [httpC multiPartUploadWithEntityType:postAttachment.entityType entityUuid:postAttachment.entityUuid arrayPostAttachments:_d_arrPostAttachments success:succ failure:fail];
//
//
//            }
//
//        } else {
//            if ([action isEqualToString:@"save"]) {
//                [self httpSavePioneeringResult];
//            } else {
//                [self httpSubmitPioneeringResult];
//            }
//        }
//
//    };
//
//    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 %@=?",[GTOPioneering TableName],@"uuid" ];
        [db executeUpdate:strSql,_d_pioneering.uuid];
    }];
    //删除本地问题
    [dataBaseC.m_dbQueue inDatabase:^(FMDatabase *db) {
        NSString *strSql = [NSString stringWithFormat:@"DELETE FROM %@ WHERE %@=?",[GTOQuestion TableName],@"pioneeringUuid" ];
        [db executeUpdate:strSql,_d_pioneering.uuid];
    }];
    [dataBaseC.m_dbQueue inDatabase:^(FMDatabase *db) {
        NSString *strSql = [NSString stringWithFormat:@"DELETE FROM %@ WHERE %@=?",[GTOAnswer TableName],@"pioneeringUuid" ];
        [db executeUpdate:strSql,_d_pioneering.uuid];
    }];
    //删除本地图片
    [dataBaseC.m_dbQueue inDatabase:^(FMDatabase *db) {
        NSString *strSql = [NSString stringWithFormat:@"DELETE FROM %@ WHERE %@=?",[ICRPostAttachment TableName],@"pioneeringUuid" ];
        [db executeUpdate:strSql,_d_pioneering.uuid];
    }];
}
//本地删除 一个问题对应的答案的图片
- (void)localDeleteOneAnswerPhotos: (GTOAnswer *)answer {
    ICRDataBaseController *dataBaseC = [ICRDataBaseController sharedController];
    [dataBaseC.m_dbQueue inDatabase:^(FMDatabase *db) {
        NSString *strSql = [NSString stringWithFormat:@"DELETE FROM %@ WHERE %@=? AND %@=? ORDER BY %@",[ICRPostAttachment TableName],@"questionUuid",@"pioneeringUuid",@"addTime" ];
        [db executeUpdate:strSql,answer.questionUuid,answer.pioneeringUuid];
    }];
    
}
- (void)httpDeletePioneeringResult {
    [IBTLoadingView showProgressLabel:@"正在保存"];
    // [IBTLoadingView hideHUDWithText:nil];
    void (^success)(id data) = ^(id data) {
//        CLog(@"%@", data);
        [IBTLoadingView hideHUDWithText:nil];
        _d_pioneering.state = GTO_PIONEERING_STATE_INITIAL;
        [_d_pioneering saveToDBWithHandleData:NULL
                                     complete:^{
                                         
                                     }
                                         fail:^(NSError *error) {
                                             
                                             [IBTLoadingView hideHUDWithText:error.localizedDescription];
                                         }];
    };
    void (^failure)(id ) = ^(id data) {
        [IBTLoadingView hideHUDWithText:data];
//        CLog(@"%@", data);
    };
    
    ICRHTTPController *httpCtrl = [ICRHTTPController sharedController];
    [httpCtrl doPioneeringRemoveWithPioneeringUuid:_d_pioneering.uuid version:_d_pioneering.version success:success failure:failure];
    
    //本地删除
    ICRDataBaseController *dataBaseC = [ICRDataBaseController sharedController];
    [dataBaseC.m_dbQueue inDatabase:^(FMDatabase *db) {
        NSString *strSql = [NSString stringWithFormat:@"DELET * FROM %@ WHERE %@=?",[GTOPioneering TableName],@"uuid" ];
        [db executeUpdate:strSql,_d_pioneering.uuid];
    }];
}

#pragma buttton Action
- (void)seeAddressClicked {
    GTOPioneeringAddressInfoViewController *aVC = [[GTOPioneeringAddressInfoViewController alloc]initWithPioneering:_d_pioneering];
    [self PushViewController:aVC animated:YES];
}
#pragma  bottomViewDelegate
- (void)bottomView:(GXFBottomView *)bottomView oneButtonClicked:(UIButton *)oneBtn {
    
    [self PopViewControllerAnimated:YES];
    
    //    GTOPioneeringListViewController *pioneeringListVC = [[GTOPioneeringListViewController alloc]init];
    //    [self PushViewController:pioneeringListVC animated:YES];
}
- (void)bottomView:(GXFBottomView *)bottomView  leftButtonClicked:(UIButton *)leftBtn {
    switch (bottomView.tag) {
        case kBottomViewTwoSaveSubmittedTag:
        {
            //提交
            // [self httpSubmitPioneeringResult];
            [self upLoadFlieWithAction: @"save"];
        }
            break;
            //        case kBottomViewTwoBackSaveTag:
            //        {
            //            [self PopViewControllerAnimated:YES];
            //        }
            //            break;
        default:
            break;
    }
    
    
    
}
- (void)bottomView:(GXFBottomView *)bottomView  RightButtonClicked:(UIButton *)rightBtn {
    switch (bottomView.tag) {
        case kBottomViewTwoSaveSubmittedTag:
        {
            //提交
            UIAlertView *alerV = [[UIAlertView alloc]initWithTitle:@"确认提交？" message:@"" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确认", nil];
            [alerV show];
            //            [self upLoadFlieWithAction: @"submitted"];
            //[self httpSavePioneeringResult];
        }
            break;
            //        case kBottomViewTwoBackSaveTag:
            //        {
            //            //保存
            //            [self httpSavePioneeringResult];
            //        }
            //            break;
        default:
            break;
    }
    
    
}
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    if (buttonIndex == 1) {
        [self upLoadFlieWithAction: @"submitted"];
    }
}
//#pragma Button Action
//- (void)sumbitResultClicked {
//
//
//}
//- (void)backClicked {
////    GTOEditPioneeringViewController *editPVC = [[GTOEditPioneeringViewController alloc]initWithPioneering:_d_pioneering];
////   // [self presentViewController:editPVC animated:YES completion:nil];
////    [self PushViewController:editPVC animated:NO];
//
//
//    [self PopViewControllerAnimated:YES];
//   // [super disMissSelf];///great!!!
//
//}
- (void)modifyClicked: (UIButton *)btn {
    
}
#pragma GTOPatrolPlanResultHeaderItemDelegate
// VI检查结果中：不同区的headerView
- (void)patrolPlanResultHeaderItem: (GTOPatrolPlanResultHeaderItem *)resultHeaderItem
                      andIsDisplay: (BOOL)isDisplay {
    NSInteger aIndex = resultHeaderItem.tag - 2;
    
    
    NSMutableArray *muArrDisplayRs = [NSMutableArray array];
    [muArrDisplayRs addObjectsFromArray:_d_pioneering.arrDisplayResults];
    GTODisplayResult *displayR = [GTODisplayResult DBObject];
    [displayR praseFromJsonDict:_d_pioneering.arrDisplayResults[aIndex]];
    displayR.isDisplay = !displayR.isDisplay;
    for (int count = 0; count < _d_pioneering.arrDisplayResults.count; count++) {
        if (count == aIndex) {
            [muArrDisplayRs replaceObjectAtIndex:aIndex withObject:[displayR dictForCommit]];
            break;
        }
        
    }
    
    _d_pioneering.arrDisplayResults = muArrDisplayRs;
    [_d_pioneering saveToDBWithHandleData:NULL complete:^{
        [_c_tableView reloadData];
    } fail:nil];
    
}
@end
