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

#import "GTOQuestionBaseViewController.h"
#import "GTOQuestionManager.h"
#import "GTOPioneering.h"
#import "GTOLicence.h"

#import "GTOQSingleSelectViewController.h"
#import "GTOQMutiSelectViewController.h"
#import "GTOQAViewController.h"
#import "GTOQScoreViewController.h"
#import "GTOQStoreStudyViewController.h"
#import "GTOQReseachViewController.h"
#import "GTOQStarViewController.h"
#import "GTOQSingleScoreViewController.h"

#import "GTOQResultViewController.h"

#import "IBTImagePicker.h"
#import "ICRAttachmentView.h"
#import "ICRStoreResult.h"
#import "IBTFileManager.h"
#import "JTRecordView.h"
#import "ICRTask.h"
#import "ICRPostTask.h"
#import "ICRAttachment.h"
#import "ICRPostAttachment.h"
#import "JTImagePreviewer.h"


#define F_GAP   (5)
#define SELECT_PAGE 100
@interface GTOQuestionBaseViewController ()
<
IBTImagePickerDelegate,
// ICRTaskEditViewDelegate,
UITextFieldDelegate,
ICRAttachmentViewDelegate,
UIAlertViewDelegate
>
{
    BOOL m_bIsLoaded;
    
}

typedef NS_ENUM(NSUInteger,alertViewTag) {
    kAlertViewPageTag = 0,
    kAlertViewDeleteTag
};
@property (strong,nonatomic) UIView *c_alertView;
@property (strong,nonatomic) UIView *c_alertInfo;
@property (strong,nonatomic) UITextField *c_pageTextF;
@property (nonatomic, assign) NSInteger d_selectPage;
//@property (assign, nonatomic) BOOL d_isDownLoadImg;//是否是从网络上下载的图片


//@property (nonatomic, strong) ICRPostAttachment* d_postAttachment;
@property (nonatomic, strong) NSMutableArray *d_muArrPhotos;
@property (assign, nonatomic) NSUInteger d_removeIndex;

@end

@implementation GTOQuestionBaseViewController
- (instancetype)initWithQuestion:(GTOQuestion *)question answer:(GTOAnswer *)answer {
    switch (question.type) {
        case kICRQestionTypeSingleSel://0
            self = [[GTOQSingleSelectViewController alloc] init];
            break;
        case kICRQestionTypeMultipleSel://1
            self = [[GTOQMutiSelectViewController alloc] init];
            break;
        case kICRQestionTypeReply://2  回复类
            self = [[GTOQAViewController alloc] init];
            break;
        case kICRQestionTypeScore://3  评分类
            self = [[GTOQScoreViewController alloc] init];
            break;
        case kICRQestionTypeStoreInv://4 库存调查类
            self = [[GTOQStoreStudyViewController alloc] init];
            break;
        case kICRQestionTypeSpeciesInv://5 品类调查类
            self = [[GTOQReseachViewController alloc] init];
            break;
        case kICRQestionTypeStarNum://6  星数类
            self = [[GTOQStarViewController alloc] init];
            break;
        case kICRQestionTypeSingleScore://7
            self = [[GTOQSingleScoreViewController alloc] init];
            break;
        default:
            // self = [[ICRQSingleSelectViewController alloc] init];
            self = [super init];
            break;
    }
    
    if (!self) {
        return nil;
    }
    
    self.d_question = question;
    self.d_answer = answer;
    
    [self p_setupDefaultAnswer];
    
    return self;
    
}
- (instancetype)initWithQuestion:(GTOQuestion *)question {
    switch (question.type) {
        case kICRQestionTypeSingleSel://0
            self = [[GTOQSingleSelectViewController alloc] init];
            break;
        case kICRQestionTypeMultipleSel://1
            self = [[GTOQMutiSelectViewController alloc] init];
            break;
        case kICRQestionTypeReply://2  回复类
            self = [[GTOQAViewController alloc] init];
            break;
        case kICRQestionTypeScore://3  评分类
            self = [[GTOQScoreViewController alloc] init];
            break;
        case kICRQestionTypeStoreInv://4 库存调查类
            self = [[GTOQStoreStudyViewController alloc] init];
            break;
        case kICRQestionTypeSpeciesInv://5 品类调查类
            self = [[GTOQReseachViewController alloc] init];
            break;
        case kICRQestionTypeStarNum://6  星数类
            self = [[GTOQStarViewController alloc] init];
            break;
        case kICRQestionTypeSingleScore://7
            self = [[GTOQSingleScoreViewController alloc] init];
            break;
        default:
            // self = [[ICRQSingleSelectViewController alloc] init];
            self = [super init];
            break;
    }
    
    if (!self) {
        return nil;
    }
    
    self.d_question = question;
    [self p_setupDefaultAnswer];
    
    return self;
    
    
}
- (void)p_setupDefaultAnswer {
    if (!self.d_answer) {
        self.d_answer = [GTOAnswer DBObject];
        //self.m_answer.content = @"";
    }
    GTOQuestionManager *mgr = [GTOQuestionManager sharedManager];
    
    
    //外键设置
    self.d_answer.uuid = _d_question.uuid;//问题的id
    if (mgr.d_pioneering) {
        self.d_answer.pioneeringUuid = mgr.d_pioneering.uuid;
    }
    if (mgr.d_licence) {
        self.d_answer.licenceUuid = mgr.d_licence.uuid;
    }
    self.d_answer.questionUuid = _d_question.uuid;//问题的id
    self.d_answer.type = _d_question.type;
    self.d_answer.category = _d_question.category;
    //self.d_answer.lineNo = _d_question.lineNo;
    // self.d_answer.uuid = [[ICRUserUtil sharedInstance] mobileID];//[NSString stringWithFormat:@"%@%@",_d_answer.pioneeringUuid,_d_answer.questionUuid];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    UIBarButtonItem *backItem = [[UIBarButtonItem alloc]init];
    backItem.title = @"";
    self.navigationItem.backBarButtonItem = backItem;
    
    UIBarButtonItem *rightBtnItem = [[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"search"] style:UIBarButtonItemStylePlain target:self action:@selector(selectProblem)];
    self.navigationItem.rightBarButtonItem = rightBtnItem;
    
    //问题明细 QuestionDetail    ？？？？？
    NSSortDescriptor *sort = [NSSortDescriptor sortDescriptorWithKey:@"index" ascending:YES];
    self.m_arrOptions = [self.d_question.details sortedArrayUsingDescriptors:@[sort]];//seq:库存或调研题的序号
    
    [self p_setupSubviews];
    [self p_loadPhotos];
    [self registerForKVO];
}
- (void)viewDidAppear:(BOOL)animated {
    
    [super viewDidAppear:YES];
}
//- (void) p_loadPhotos {
//    ICRDatabaseFetchBlock fetchBlk = ^FMResultSet *(FMDatabase *db) {
//        if(_d_answer.pioneeringUuid && !_d_answer.licenceUuid) {
//            NSString *sql = [NSString stringWithFormat:@"SELECT * FROM %@ WHERE %@=? AND %@=? ORDER BY %@",[ICRPostAttachment TableName],@"questionUuid",@"pioneeringUuid",@"addTime"];
//            return [db executeQuery:sql,_d_answer.questionUuid,_d_answer.pioneeringUuid];
//        } else {
//            NSString *sql = [NSString stringWithFormat:@"SELECT * FROM %@ WHERE %@=? AND %@=? ORDER BY %@",[ICRPostAttachment TableName],@"questionUuid",@"licenceUuid",@"addTime"];
//            return [db executeQuery:sql,_d_answer.questionUuid,_d_answer.licenceUuid];
//        }
//    };
//    __weak typeof (self) weakSelf = self;
//    ICRDatabaseFetchResultsBlock fetchResultBlk = ^(NSArray *fetchedObjects) {
//        __strong __typeof(weakSelf) strongSelf = weakSelf;
//        if (fetchedObjects.count > 0) {
//            if (!_d_muArrPhotos) {
//                self.d_muArrPhotos = [NSMutableArray arrayWithArray:fetchedObjects];
//            }
//            self.d_muArrPhotos = [NSMutableArray arrayWithArray:fetchedObjects];
//            for(ICRPostAttachment *postAttachment in fetchedObjects) {
//                if(postAttachment.is_localPhoto) {
//                    BOOL isHave = [[NSFileManager defaultManager] fileExistsAtPath:postAttachment.filePath];
//                    if(isHave) {
//                        CLog(@"%@",postAttachment.filePath);
//                        UIImage *img = [[UIImage alloc]initWithContentsOfFile:postAttachment.filePath];
//                        [self addAttachment:img isLocalPhoto:YES ];
//                    }
//                    //                            if (postAttachment.content) {
//                    //                                NSData *imageData = [NSData dataFromBase64String:postAttachment.content];
//                    //                                UIImage *image = [UIImage imageWithData:imageData];
//                    //                                [self addAttachment:image];
//                    //                            }
//                }else {
//                    if (postAttachment.fileUrl) {
//                        [self addAttachment:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",HTTP_LOCAL_BASE_URL ,postAttachment.fileUrl]]isLocalPhoto:NO];
//                    }
//                }
//            }
//            
//        }
//        
//    };
//    ICRDataBaseController *dbCtl = [ICRDataBaseController sharedController];
//    [dbCtl runFetchForClass:[ICRPostAttachment class]
//                 fetchBlock:fetchBlk
//          fetchResultsBlock:fetchResultBlk];
//}
- (void)p_loadPhotos {

    //显示后台上面的附件 网络上获取附件
    if (_d_answer.resultAttachmentUrls.count > 0) {
        for(NSDictionary *dict in _d_answer.resultAttachmentUrls){
            ICRPostAttachment *postAttachment = [ICRPostAttachment DBObject];
            [postAttachment praseFromJsonDict:dict];
//            self.d_isDownLoadImg = YES;
            [self addAttachment:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",HTTP_LOCAL_BASE_URL ,postAttachment.fileUrl]] isLocalPhoto:NO];
        }
    } else {
        //加载本地图片
        ICRDatabaseFetchBlock fetchBlk = ^FMResultSet *(FMDatabase *db) {
//            if(_d_answer.pioneeringUuid && !_d_answer.licenceUuid) {
//                NSString *sql = [NSString stringWithFormat:@"SELECT * FROM %@ WHERE %@=? AND %@=? ORDER BY %@",[ICRPostAttachment TableName],@"questionUuid",@"pioneeringUuid",@"addTime"];
//                return [db executeQuery:sql,_d_answer.questionUuid,_d_answer.pioneeringUuid];
//            } else {
                NSString *sql = [NSString stringWithFormat:@"SELECT * FROM %@ WHERE %@=? AND %@=? ORDER BY %@",[ICRPostAttachment TableName],@"questionUuid",@"licenceUuid",@"addTime"];
                return [db executeQuery:sql,_d_answer.questionUuid,_d_answer.licenceUuid];
//            }
        };

        __weak typeof (self) weakSelf = self;
        ICRDatabaseFetchResultsBlock fetchResultBlk = ^(NSArray *fetchedObjects) {
            __strong __typeof(weakSelf) strongSelf = weakSelf;
            if (fetchedObjects.count > 0) {
//                if (!_d_postAttachment) {
//                    self.d_postAttachment = fetchedObjects[0];
//                }
                if (!_d_muArrPhotos.count) {
                    self.d_muArrPhotos = [NSMutableArray arrayWithArray:fetchedObjects];
                    for(ICRPostAttachment *postAttachment in fetchedObjects) {
                        NSString *imgPath = [[IBTCommon archivePathForTmpImages] stringByAppendingPathComponent:postAttachment.fileName];
                        BOOL isHave = [[NSFileManager defaultManager] fileExistsAtPath:imgPath];
                        if(isHave) {
                            UIImage *img = [[UIImage alloc] initWithContentsOfFile:imgPath];
                            [self addAttachment:img isLocalPhoto:YES];
                        }
                        //
                        //                            if (postAttachment.content) {
                        //                                NSData *imageData = [NSData dataFromBase64String:postAttachment.content];
                        //                                UIImage *image = [UIImage imageWithData:imageData];
                        //                                [self addAttachment:image];
                        //                            }

                    }
                }
            }
        };

        ICRDataBaseController *dbCtl = [ICRDataBaseController sharedController];
        [dbCtl runFetchForClass:[ICRPostAttachment class]
                     fetchBlock:fetchBlk
              fetchResultsBlock:fetchResultBlk];
        //        } else {
        //
        //        }
//        if (_d_answer.task) {
//            ICRPostTask *pTask = [ICRPostTask DBObject];
//            [pTask praseFromLocalDict:_d_answer.task];
//
//            [self addAttachment:pTask];
//        }
//
//        if (_d_answer.voice) {
//            ICRPostAttachment *pVoice = [ICRPostAttachment DBObject];
//            [pVoice praseFromJsonDict:_d_answer.voice];
//
//            NSData *voiceData = [NSData dataFromBase64String:pVoice.content];
//
//            [self addAttachment:voiceData];
//        }

    }

}

//重写 父类：IBTUIViewController中的左边按钮的方法
- (void)disMissSelf {  //每次退出时写到数据库中  dismissView
    //因为这个方法是左边自定义按钮的事件相应 为什么子类退出时没有调用这个方法？？？
    //  [IBTLoadingView showProgressLabel:@"正在保存..."];
    
    //    GTOQuestionManager *mgr = [GTOQuestionManager sharedManager];
    //    ICRStoreResult *storeR = [mgr getStoreResult];
    
    if(!self.d_answer.bIsAnswered) {
        [super disMissSelf];
        return;
    }
    [_d_answer saveToDBWithHandleData:NULL
                             complete:^{
                                 [IBTLoadingView hideHUDWithText:nil];
                                 [super disMissSelf];
                                 // [ICRQuestionManager sharedManager].m_patrolPlan = nil;
                                 
                             }
                                 fail:^(NSError *error) {
                                     
                                     [IBTLoadingView hideHUDWithText:error.localizedDescription];
                                 }];
    
}


- (void)dealloc {
    [self unregisterFromKVO];
}

#pragma mark - Private Method
- (void)p_setupSubviews {
    
    self.view.backgroundColor = [UIColor colorWithR:240 g:246 b:255 a:1];
    
    self.c_titleLabel = [[IBTUILabel alloc] init];//问题题号和问题标题
    _c_titleLabel.numberOfLines = 0;
    _c_titleLabel.font = [UIFont boldSystemFontOfSize:18];
    _c_titleLabel.textColor = [UIColor grayColor];
    _c_titleLabel.text = [NSString stringWithFormat:@"%@.%@",@(self.d_questionIndex + 1),self.d_question.title];
    
    CGFloat fMargin = 15.0f;
    CGSize size = CGSizeMake(self.view.width - 2 * fMargin,CGFLOAT_MAX);
    size = [self.c_titleLabel widthLimitedSizeThatFits:size];
    _c_titleLabel.frame = (CGRect){
        .origin.x = fMargin,
        .origin.y = F_GAP,
        .size = size
    };
    
    
    GTOQuestionManager *mgr = [GTOQuestionManager sharedManager];
    UIViewController *qVC = [mgr questionViewControlAtIndex:self.d_questionIndex + 1];
    BOOL isFirst = self.d_questionIndex == 0 ? YES : NO;
    BOOL isLast = qVC ? NO : YES;
    CGFloat fHeight = 300; //附加信息包含nextbutton
    //    self.c_helperView = [[ICRQuestionHelperView alloc]initWithFrame:(CGRect){
    //        .origin.x = 0,
    //        .origin.y = self.view.height - fHeight,
    //        .size.width = self.view.width,
    //        .size.height = fHeight}
    //                                    isFirst:isFirst isLast:isLast];
    
    CGRect rect = CGRectMake(0, self.view.height - fHeight, self.view.width, fHeight);
    self.c_helperView = [[ICRQuestionHelperView alloc]initWithFrame:rect isFirst:isFirst isLast:isLast notEdit:_d_notEdit];
    _c_helperView.autoresizingMask = UIViewAutoresizingFlexibleTopMargin;
    _c_helperView.m_photoAttachView.delegate = self;
    if(_d_notEdit) {
        _c_helperView.m_photoAttachView.m_addButton.hidden = YES;
        _c_helperView.m_inputTxtF.userInteractionEnabled = NO;
    } else {
        [_c_helperView.m_photoAttachView.m_addButton addTarget:self
                                                        action:@selector(onShowImagePicker:)
                                              forControlEvents:UIControlEventTouchUpInside];
    }
    _c_helperView.m_inputTxtF.delegate = self;
    if (_d_answer.resultRemark) {
        _c_helperView.m_inputTxtF.text = _d_answer.resultRemark;
    }
    //    [_c_helperView.m_taskAttachView.m_addButton addTarget:self
    //                                                   action:@selector(onAddTask:)//关联任务
    //                                         forControlEvents:UIControlEventTouchUpInside];
    //
    //    [_c_helperView.m_voiceAttachView.m_addButton addTarget:self
    //                                                    action:@selector(onStartRecord:)//开始录音
    //                                          forControlEvents:UIControlEventTouchDown | UIControlEventTouchDownRepeat];
    //    [_c_helperView.m_voiceAttachView.m_addButton addTarget:self
    //                                                    action:@selector(onEndRecord:)//结束录音
    //                                          forControlEvents:UIControlEventTouchUpInside|UIControlEventTouchDragOutside];
    
    
    if (isLast) {
        [_c_helperView.m_nextBtn addTarget:self
                                    action:@selector(onNextBtnAction:)
                          forControlEvents:UIControlEventTouchUpInside];
    } else {
        [_c_helperView.m_nextBtn addTarget:self
                                    action:@selector(onNextBtnAction:)
                          forControlEvents:UIControlEventTouchUpInside];
        [_c_helperView.m_beforeBtn addTarget:self
                                      action:@selector(onBeforeBtnAction:)
                            forControlEvents:UIControlEventTouchUpInside];
    }
    [self initScrollViewWithRect:(CGRect){//具体问题内容放到了scrollview上，当内容多时可拖动，
        .origin.x = 0,
        .origin.y = _c_titleLabel.bottom + F_GAP,
        .size.width = self.view.width,
        .size.height = self.view.height - _c_titleLabel.bottom - F_GAP
    }];
    
    [self.c_contentScrollView autoresizingWithStrechFullSize];
    [self.c_contentScrollView setContentInsetTop:0 andBottom:_c_helperView.top];//改变contentInset
    
    [self.view addSubview:_c_titleLabel];
    [self.view addSubview:_c_contentScrollView];
    [self.view addSubview:_c_helperView];
}


- (void)initScrollViewWithRect:(CGRect)rect {
    IBTUIScrollView *scrollV = [[IBTUIScrollView alloc] initWithFrame:rect];
    scrollV.bHandleKeyboard = YES;
    self.c_contentScrollView = scrollV;
}
- (void)addAttachment:(id)oAtt isLocalPhoto: (BOOL)isLocal{ //
    
    SEL selector = NULL;
    
    UIImage *iconImg;
    ICRAttachmentView *attachView = nil;
    
    if ([oAtt isKindOfClass:[UIImage class]]) {//
        iconImg = oAtt;//[UIImage imageNamed:@"icon_task_default"];
        selector = @selector(onTapImage:);
        attachView = self.c_helperView.m_photoAttachView;
    } else {
        iconImg = oAtt;
        selector = @selector(onTapImageView:);
        attachView = self.c_helperView.m_photoAttachView;
    }
    //    else if ([oAtt isKindOfClass:[NSData class]]) {//录音：为nsdata
    //        iconImg = [UIImage imageNamed:@"icon_voice"];
    //        selector = @selector(onAttVoicePlay:);
    //        attachView = self.c_helperView.m_voiceAttachView;
    //    }
    //    else if ([oAtt isKindOfClass:[UIImage class]]) {//
    //        iconImg = oAtt;
    //        selector = @selector(onTapImage:);
    //        attachView = self.c_helperView.m_photoAttachView;
    //    }
    
    ICRAttachmentUnit *attV = [[ICRAttachmentUnit alloc] initWithFrame:(CGRect){
        .origin.x = 0,
        .origin.y = 0,
        .size.width = IBT_ATTACH_UNIT_DEFAULT_WIDTH,
        .size.height = IBT_ATTACH_UNIT_DEFAULT_WIDTH
    }];
    
    if(!isLocal) {
        attachView.isDownImg = YES;
        attV.m_imageView.backgroundColor = [UIColor grayColor];
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            if ((_d_pioneering && [_d_pioneering.state isEqualToString:GTO_PIONEERING_STATE_INITIAL])
                || (_d_licence && [_d_licence.state isEqualToString:GTO_LICENCE_STATE_INITIAL])) {
                [attV updateWithType:kATTCloseBtn masker:nil placeHolder:nil image:iconImg title:nil];
            } else {
                [attV updateWithType:kATTNormal masker:nil placeHolder:nil image:iconImg title:nil];
            }
            
        });
    } else {
        
        [attV updateWithType:kATTCloseBtn masker:nil placeHolder:nil image:iconImg title:nil];
    }
    
    attV.m_oAttachmentWrap = oAtt;
    
    [attV addTarget:self
             action:selector
   forControlEvents:UIControlEventTouchUpInside];
    
    [attachView addContentAttachmentView:attV];
}


#pragma mark - Action
- (void)onShowImagePicker:(__unused id)sender {
    [[GTOQuestionManager sharedManager].m_imagePicker showImagePickerTitle:nil
                                                                 mediaType:kIBTMediaBImage
                                                                  editable:NO
                                                        fromViewController:self];
}

- (void)onAddTask:(__unused id)sender {
    [self openEditTaskView:nil];
}

- (void)onTapTask:(ICRAttachmentUnit *)unit {
    ICRPostTask *pTask = unit.m_oAttachmentWrap;
    [self openEditTaskView:[ICRTask taskFromPostTask:pTask]];
}
- (void)openEditTaskView:(ICRTask *)task {
    
}
- (void)onTapImage:(ICRAttachmentUnit *)unit {
    
    CGRect rect = [self.view.window convertRect:unit.frame
                                       fromView:unit.superview];
    
    UIImage *img = unit.m_oAttachmentWrap;
    JTImagePreviewer *ipv =
    [[JTImagePreviewer alloc] initWithViewController:self
                                           tempImage:img
                                                 url:nil
                                           startRect:rect];
    [ipv show];
}
- (void)onTapImageView:(ICRAttachmentUnit *)unit {
    CGRect rect = [self.view.window convertRect:unit.frame
                                       fromView:unit.superview];
    
    UIImage *img = unit.m_imageView.image;
    JTImagePreviewer *ipv =
    [[JTImagePreviewer alloc] initWithViewController:self
                                           tempImage:img
                                                 url:nil
                                           startRect:rect];
    [ipv show];
    
}
- (void)selectProblem {
    if(!self.d_answer.bIsAnswered) {
        [super disMissSelf];
        return;
    }
    [self.d_answer saveToDBWithHandleData:NULL
                                 complete:^{
                                     [IBTLoadingView hideHUDWithText:nil];
                                     [super disMissSelf];
                                 }
                                     fail:^(NSError *error) {
                                         
                                         [IBTLoadingView hideHUDWithText:error.localizedDescription];
                                     }];
    
    //    NSInteger indexProblem = [[ICRQuestionManager sharedManager] m_maxProblemLineno];
    //    NSLog(@"maxlineno = %ld",[[ICRQuestionManager sharedManager] m_maxProblemLineno]);
    //
    //    [self creatAlphaView];
    //    [self creatAlterInfo];
}
- (void)onNextBtnAction:(__unused id)sender {
    //    GTOQuestionManager *mgr = [GTOQuestionManager sharedManager];
    //    UIViewController *qVC = [mgr questionViewControlAtIndex:self.d_questionIndex + 1];
    //    if (qVC) {
    //        [self PushViewController:qVC animated:YES];
    //    }
    //    else {
    //        // TODO
    //    }
    if(!self.d_answer.bIsAnswered) {
        [super disMissSelf];
        return;
    }
    [_d_answer saveToDBWithHandleData:NULL
                             complete:^{
                                 [IBTLoadingView hideHUDWithText:nil];
                                 [super disMissSelf];
                                 // [ICRQuestionManager sharedManager].m_patrolPlan = nil;
                                 
                             }
                                 fail:^(NSError *error) {
                                     
                                     [IBTLoadingView hideHUDWithText:error.localizedDescription];
                                 }];
    
    // [_d_answer saveToDBWithHandleData:NULL complete:nil fail:nil];
}
- (void)onBeforeBtnAction: (__unused id)sender {
    [self.d_answer saveToDBWithHandleData:NULL
                                 complete:^{
                                     [IBTLoadingView hideHUDWithText:nil];
                                     // [super disMissSelf];
                                     // [ICRQuestionManager sharedManager].m_patrolPlan = nil;
                                     
                                 }
                                     fail:^(NSError *error) {
                                         
                                         [IBTLoadingView hideHUDWithText:error.localizedDescription];
                                     }];
    [self PopViewControllerAnimated:YES];
}
- (void)onLastBtnAction: (__unused id)sender {
    // TODO
}

- (void)tap:(UIGestureRecognizer *)recognizer{
    // TODO
}
- (void)creatAlphaView{
    //UIViewController
    
    //_alertView = [[UIView alloc]initWithFrame:self.view.bounds];
    _c_alertView = [[UIView alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    _c_alertView.backgroundColor = [UIColor clearColor];
    [[UIApplication sharedApplication].keyWindow addSubview:_c_alertView];
    
    UIView *alphaView = [[UIView alloc]initWithFrame:_c_alertView.frame];
    alphaView.backgroundColor = [UIColor blackColor];
    alphaView.alpha = 0.3;
    [_c_alertView addSubview: alphaView];
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tap:)];
    [tap setDelegate:(id<UIGestureRecognizerDelegate>)self];
    tap.numberOfTouchesRequired = 1;
    tap.numberOfTapsRequired = 1;
    [_c_alertView setTag:10000];
    [_c_alertView addGestureRecognizer:tap];
    
}
- (void)creatAlterInfo {
    CGFloat alertInfoY = 100+ 64;
    CGFloat alertInfoW = CGRectGetWidth(self.view.frame);
    CGFloat alertInfoH = 250;//CGRectGetHeight(self.view.bounds)- CGRectGetHeight(_m_headImageView.frame);
    CGFloat padding = 10;
    if (!_c_alertInfo) {
        _c_alertInfo = [[UIView alloc]initWithFrame:CGRectMake(0,alertInfoY,alertInfoW,alertInfoH)];
        [_c_alertInfo setBackgroundColor:[UIColor clearColor]];
        [_c_alertView  addSubview:_c_alertInfo];
        
        UIView *info = [[UIView alloc]initWithFrame:CGRectMake(0, padding, alertInfoW, alertInfoH - 64)];
        info.backgroundColor = [UIColor whiteColor];
        [_c_alertInfo addSubview:info];
        
        CGFloat topH = 40; CGFloat W = alertInfoW;
        CGFloat otherH = (CGRectGetHeight(info.bounds) - (topH + padding) * 2.0)/4.0;
        UILabel *lblCome = [[UILabel alloc]initWithFrame:CGRectMake(0, 0,W , topH)];
        lblCome.font = [UIFont systemFontOfSize:20];
        lblCome.text = @"填写要跳转的问题页数";
        [lblCome setTextAlignment:NSTextAlignmentCenter];
        [info addSubview:lblCome];
        
        UIButton *btnClose = [[UIButton alloc]initWithFrame:CGRectMake(W - padding - 40, 0, 40, topH)];
        [btnClose setTitleColor:ICR_BLUE_BTN_COLOR  forState:UIControlStateNormal];
        [btnClose setTitle:@"关闭" forState:UIControlStateNormal];
        [btnClose addTarget:self action:@selector(closed) forControlEvents:UIControlEventTouchUpInside];
        [info addSubview:btnClose];
        
        UILabel *attentionLbl = [[UILabel alloc]initWithFrame:CGRectMake(0, lblCome.bottom, W, topH)];
        attentionLbl.font = [UIFont systemFontOfSize:20];
        attentionLbl.text = [NSString stringWithFormat:@"填写页数范围：%d ~ %ld",0,[[GTOQuestionManager sharedManager] d_maxProblemLineno]];//0代表跳转到巡检汇总
        [attentionLbl setTextAlignment:NSTextAlignmentCenter];
        [info addSubview:attentionLbl];
        
        UIView *infoV = [[UIView alloc]initWithFrame:CGRectMake((info.width - 100)*0.5, attentionLbl.bottom + 10, 100, topH)];
        [info addSubview:infoV];
        
        CGRect rect = CGRectMake(0, 0, 20, infoV.height);
        UILabel *lbl1 = [self p_labelWithFrame:rect title:@"第" font:[UIFont systemFontOfSize:17] textAlignment:NSTextAlignmentLeft];
        rect = CGRectMake(lbl1.right, 0, infoV.width - lbl1.width * 2, infoV.height);
        UITextField *textF = [[UITextField alloc]initWithFrame:rect];
        textF.textAlignment = NSTextAlignmentCenter;
        textF.keyboardType =  UIKeyboardTypePhonePad;
        textF.delegate = self;
        textF.tag = SELECT_PAGE;
        textF.layer.borderColor = [[UIColor grayColor] CGColor];
        textF.layer.borderWidth = 1.0;
        textF.layer.cornerRadius = 5;
        textF.layer.masksToBounds = YES;
        self.c_pageTextF = textF;
        
        rect = CGRectMake(textF.right, 0, lbl1.width, infoV.height);
        UILabel *lbl2 = [self p_labelWithFrame:rect title:@"页" font:[UIFont systemFontOfSize:17] textAlignment:NSTextAlignmentRight];
        [infoV addSubview:lbl1];
        [infoV addSubview:lbl2];
        [infoV addSubview:textF];
        
        UIButton *suretBtn = [[UIButton alloc]initWithFrame:CGRectMake(0, info.height - topH, W, topH)];
        [suretBtn setBackgroundColor:ICR_ORANGE_BTN_COLOR ];
        [suretBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [suretBtn setTitle:@"确认" forState:UIControlStateNormal];
        [suretBtn addTarget:self action:@selector(sureSelectionClicked:) forControlEvents:UIControlEventTouchUpInside];
        [info addSubview:suretBtn];
        
        
    }
}
- (void)closed {
    if (_c_alertInfo) {
        [_c_alertInfo removeFromSuperview];
        _c_alertInfo = nil;
    }
    
    if (_c_alertView) {
        [_c_alertView removeFromSuperview];
        _c_alertView = nil;
    }
    
    
}
- (void)sureSelectionClicked:(UIButton *)btn {
    btn.tag = self.d_selectPage;
    GTOQuestionManager *mgr = [GTOQuestionManager sharedManager];
    CLog(@"%ld",mgr.m_vcs.count);
    if (btn.tag > mgr.m_vcs.count) {
        UIAlertView *alertV = [[UIAlertView alloc]initWithTitle:@"提示" message:@"输入的页数非法" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:nil];
        alertV.tag = kAlertViewPageTag;
        [alertV show];
        return;
    }
    if (_c_alertInfo) {
        [_c_alertInfo removeFromSuperview];
        _c_alertInfo = nil;
    }
    
    if (_c_alertView) {
        [_c_alertView removeFromSuperview];
        _c_alertView = nil;
    }
    
    if (self.d_questionIndex != btn.tag -1) {
        
        self.navigationController.viewControllers = mgr.m_vcs;
        UIViewController *qVC = [self.navigationController.viewControllers objectAtIndex:btn.tag - 1];
        NSMutableArray *muarrVCs = [NSMutableArray array];
        for  ( UIViewController *qVC in self.navigationController.viewControllers) {
            CLog(@"%@",qVC);
            [muarrVCs addObject:qVC];
        }
        
        CLog(@"%ld",self.navigationController.viewControllers.count);
        [self PopToViewController:qVC animated:YES];
        
        
    }
    
}
- (UILabel *)p_labelWithFrame: (CGRect)aFrame
                        title: (NSString *)aTitle
                         font: (UIFont *)aFont
                textAlignment: (NSTextAlignment)aTextAlignmet {
    UILabel *lbl = [[UILabel alloc]initWithFrame:aFrame];
    lbl.text = aTitle;
    lbl.textAlignment = aTextAlignmet;
    lbl.font = aFont;
    return lbl;
}
#pragma mark - Public Method

- (void)openResultView {
    // [IBTLoadingView showProgressLabel:@"正在保存..."];
    
    GTOQuestionManager *mgr = [GTOQuestionManager sharedManager];
    GTOQResultViewController *rVC = [[GTOQResultViewController alloc] initWithPioneering:mgr.d_pioneering];
    [self PushViewController:rVC animated:YES];
    //    __weak typeof(self)weakSelf = self;
    //    [_d_answer saveToDBWithHandleData:NULL
    //                          complete:^{
    //                              __strong __typeof(weakSelf)strongSelf = weakSelf;
    //                              [IBTLoadingView hideHUDWithText:nil];
    //                              GTOQResultViewController *rVC = [[GTOQResultViewController alloc] initWithPioneering:mgr.d_pioneering];
    //                              [strongSelf PushViewController:rVC animated:YES];
    //                          }
    //                              fail:^(NSError *error) {
    //
    //                                  [IBTLoadingView hideHUDWithText:error.localizedDescription];
    //                              }];
    
    
    
}



#pragma mark - UITextFieldDelegate
- (void)textFieldDidEndEditing:(UITextField *)textField {
    if (textField.tag == SELECT_PAGE) {
        self.d_selectPage = [textField.text integerValue];
    }
    
}
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    //    if (self.d_question.type == kICRQestionTypeReply) {
    //        self.d_answer.resultContent = self.c_helperView.m_inputTxtF.text;
    //    }
    [[NSNotificationCenter defaultCenter] postNotificationName:KNOTIFICATION_QUESTION_KEYBOARD_HIDE object:nil];
    [textField resignFirstResponder];
    return YES;
}

#pragma mark - IBTImagePickerDelegate
- (void)imagePicker:(IBTImagePickerController *)picker
     didImagePicked:(UIImage *)image referenceURL:(NSURL *)imageUrl {
    IBTFileData *imgFile = [IBTCommon saveImageToLocal:image];
    
    ICRPostAttachment *attE = [[ICRPostAttachment alloc] init];
    if(_d_answer.pioneeringUuid && !_d_answer.licenceUuid) {
        attE.entityType = GTO_ENTITYTYPE_PIONEER_ANSWER;
        attE.pioneeringUuid = _d_answer.pioneeringUuid;
    } else {
        attE.entityType = GTO_ENTITYTYPE_LICENCE_ANSWER;
        attE.licenceUuid = _d_answer.licenceUuid;
    }
    attE.questionUuid = _d_answer.questionUuid;
    attE.fileName = imgFile.fileName;
    // attE.content = [imgFile.fileData base64EncodedString];
    attE.filePath = imgFile.filePath;
    attE.uuid = [[ICRUserUtil sharedInstance] mobileID];
    attE.addTime = [[NSDate date] httpParameterString];
    attE.is_localPhoto = YES;
    attE.is_delete = NO;
    if(!_d_answer.resultAttachmentId) {
        self.d_answer.resultAttachmentId = [[ICRUserUtil sharedInstance] mobileID];
        [self.d_answer saveToDBWithHandleData:NULL complete:^{
            attE.entityUuid = self.d_answer.resultAttachmentId;
            if (!self.d_muArrPhotos) {
                self.d_muArrPhotos = [NSMutableArray array];
            }
            
            [attE saveToDBWithHandleData:NULL complete:NULL fail:NULL];
            [self.d_muArrPhotos addObject:attE];
            [self addAttachment:image isLocalPhoto:YES];
            
        } fail:NULL];
        [self.d_answer saveToDBWithHandleData:NULL complete:NULL fail:NULL];
    } else {
        attE.entityUuid = self.d_answer.resultAttachmentId;
        if (!self.d_muArrPhotos) {
            self.d_muArrPhotos = [NSMutableArray array];
        }
        
        [attE saveToDBWithHandleData:NULL complete:NULL fail:NULL];
        [self.d_muArrPhotos addObject:attE];
        [self addAttachment:image isLocalPhoto:YES];
        
    }
    //   if (!self.d_postAttachment) {
    //        self.d_postAttachment = attE;
    //        self.d_postAttachment.entityUuid = [[ICRUserUtil sharedInstance] mobileID];
    //    }
    
}



- (void)imagePicker:(IBTImagePickerController *)picker
didVideoPickedWithURL:(NSURL *)videoUrl {
    
}
#pragma ICRAttachmentViewDelegate
- (void)attachmentView:(ICRAttachmentView *)attachmentView removeContentAttachmentViewAtIndex:(NSUInteger)uiIndex {
    ICRPostAttachment *postAttachment = _d_muArrPhotos[uiIndex];
    //如果是本地添加的可以直接从数据中删除，不用调用接口
    if (!postAttachment.is_localPhoto) {
        postAttachment.is_delete = YES;
        [self.d_muArrPhotos removeObjectAtIndex:uiIndex];
        [postAttachment saveToDBWithHandleData:NULL complete:NULL fail:NULL];
    } else {
        [self removePhotoAtIndex:self.d_removeIndex];
    }
    //    UIAlertView *alertV =[ [UIAlertView alloc]initWithTitle:@"是否删除图片" message:@"" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
    //    self.d_removeIndex = uiIndex;
    //    alertV.tag = kAlertViewDeleteTag;
    //    [alertV show];
    
}
- (void)removePhotoAtIndex:(NSUInteger)uiIndex  {
    ICRPostAttachment *postAttachment = _d_muArrPhotos[uiIndex];
    ICRDataBaseController *dataBaseC = [ICRDataBaseController sharedController];
    [dataBaseC.m_dbQueue inDatabase:^(FMDatabase *db) {
        NSString *sql = [NSString stringWithFormat:@"DELETE FROM %@ WHERE %@ = ?",[ICRPostAttachment TableName],@"questionUuid"];
        [db executeUpdate:sql,postAttachment.questionUuid];
    }];
    
    [self.d_muArrPhotos removeObjectAtIndex:uiIndex];
}
//- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
//    switch (alertView.tag) {
//        case kAlertViewPageTag:
//        {
//        }
//            break;
//        case kAlertViewDeleteTag:
//        {
//            if (buttonIndex == 1) {
//                CLog(@"delet");
//                [self removePhotoAtIndex:self.d_removeIndex];
//            }
//        }
//            break;
//        default:
//            break;
//    }
//}

#pragma mark - KVO

- (void)registerForKVO {
    for (NSString *keyPath in [self observableKeypaths]) {
        [_c_helperView addObserver:self forKeyPath:keyPath options:NSKeyValueObservingOptionNew context:NULL];
    }
}

- (void)unregisterFromKVO {
    for (NSString *keyPath in [self observableKeypaths]) {
        [_c_helperView removeObserver:self forKeyPath:keyPath];
    }
}

- (NSArray *)observableKeypaths {
    return @[ @"frame" ];
}

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
    [self.c_contentScrollView setContentInsetTop:0 andBottom:self.view.height - _c_helperView.y];
}

#pragma mark - Keyboard
- (void)keyboardWillShow:(NSNotification *)note {
    // get keyboard size and loctaion
    CGRect keyboardBounds;
    [[note.userInfo valueForKey:UIKeyboardFrameEndUserInfoKey] getValue: &keyboardBounds];
    NSNumber *duration = [note.userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey];
    NSNumber *curve = [note.userInfo objectForKey:UIKeyboardAnimationCurveUserInfoKey];
    
    // Need to translate the bounds to account for rotation.
    keyboardBounds = [self.view convertRect:keyboardBounds toView:nil];
    
    // animations settings
    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationBeginsFromCurrentState:YES];
    [UIView setAnimationDuration:[duration doubleValue]];
    [UIView setAnimationCurve:[curve intValue]];
    
    // set views with new info
    
    if ([_c_helperView.m_inputTxtF isFirstResponder]) {
        _c_helperView.y = self.view.height - CGRectGetHeight(keyboardBounds) - 75;
    }
    
    // commit animations
    [UIView commitAnimations];
}

- (void)keyboardWillHide:(NSNotification *)note {
    //[_pageTextF resignFirstResponder];
    [self textFieldDidEndEditing:_c_pageTextF];
    //    if (self.d_question.type == kICRQestionTypeReply) {
    //        self.d_answer.resultContent = self.c_helperView.m_inputTxtF.text;
    //    }
    [[NSNotificationCenter defaultCenter] postNotificationName:KNOTIFICATION_QUESTION_KEYBOARD_HIDE object:nil];
    
    NSNumber *duration = [note.userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey];
    NSNumber *curve = [note.userInfo objectForKey:UIKeyboardAnimationCurveUserInfoKey];
    
    // animations settings
    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationBeginsFromCurrentState:YES];
    [UIView setAnimationDuration:[duration doubleValue]];
    [UIView setAnimationCurve:[curve intValue]];
    
    // set views with new info
    _c_helperView.y = self.view.height - _c_helperView.height;
    
    // commit animations
    [UIView commitAnimations];
}

#pragma mark - Audio

//- (void)StartRecording {
//
//    GTOQuestionManager *mgr = [GTOQuestionManager sharedManager];
//    if(qMgr.m_oAudioRecorder == nil){
//
//        qMgr.m_oAudioRecorder = [[IBTAudioRecorder alloc] init];
//        __weak typeof(qMgr)weakMgr = qMgr;
//
//        [qMgr.m_oAudioRecorder setFinishRecordingBlock:(^(IBTAudioRecorder* recorder,BOOL success){
//            __strong __typeof(weakMgr)strongMgr = weakMgr;
//
//            NSString *filePath = [recorder recorderingPath];
//            if(strongMgr.m_fRecoderTime >= m_fMinAudioRecoderDuration){
//
//                NSData *audioData = [[NSData alloc] initWithContentsOfFile:filePath];
//
//                NSString *fileName = [NSString stringWithFormat:@"ICRAUDIO-%@.mp4", [[NSDate date] YMDHMSFormatterString]];
//                ICRPostAttachment *attE = [[ICRPostAttachment alloc] init];
//                //                attE.type = @"answer";
//                //                attE.objectId = _m_answer.mobileId;
//                //                attE.filename = fileName;
//                //                attE.content = [audioData base64EncodedString];
//                //                attE.seq = @(2);
//                //                attE.attachmentType = @"answer";
//
//                self.m_answer.voice = [attE dictForCommit];
//
//                [self addAttachment:audioData];
//            }
//            else{
//                [IBTCommon runOnMainThreadWithoutDeadlocking:^{
//                    [IBTLoadingView showTips:@"录音时间太短"];
//                }];
//                [self OnAudioEndRecord];
//                [IBTFileManager removeFileAtPath:filePath];
//            }
//        })];
//        [qMgr.m_oAudioRecorder setEncodeErrorRecordingBlock:^(IBTAudioRecorder *recorder,NSError *error){
//
//            [IBTCommon runOnMainThreadWithoutDeadlocking:^{
//                [IBTLoadingView showTips:@"编码错误"];
//            }];
//            [self OnAudioEndRecord];
//        }];
//
//        [qMgr.m_oAudioRecorder setReceivedRecordingBlock:^(IBTAudioRecorder *recorder,float peakPower,float averagePower,float currentTime){
//            __strong __typeof(weakMgr)strongMgr = weakMgr;
//            CLog(@"recording, peakPower = %f,averagePower = %f,currentTime = %f",peakPower,averagePower,currentTime);
//            [self UpdateRecordPower:peakPower];
//            if (currentTime > 0) {
//                strongMgr.m_fRecoderTime = currentTime;
//            }
//        }];
//    }
//
//    qMgr.m_fRecoderTime = 0;
//    [qMgr.m_oAudioRecorder startRecordForDuration:m_fMaxAudioRecoderDuration];
//}
//
//- (void)StopRecording {
//    ICRQuestionManager *qMgr = [ICRQuestionManager sharedManager];
//    [qMgr.m_oAudioRecorder performSelector:@selector(stopRecord) withObject:nil afterDelay:.2f];
//}
//
//- (void)onAttVoicePlay:(id)sender {
//    NSData *audioData = [sender valueForKey:@"m_oAttachmentWrap"];
//
//    ICRQuestionManager *qMgr = [ICRQuestionManager sharedManager];
//
//    if (!qMgr.m_oAudioPlayer) {
//        qMgr.m_oAudioPlayer = [[IBTAVAudioPlayWrapper alloc] init];
//    }
//
//    __weak typeof(qMgr)weakMgr = qMgr;
//    [qMgr.m_oAudioPlayer playWithData:audioData
//                             complete:^(BOOL finished, NSError *error) {
//                                 __strong __typeof(weakMgr)strongMgr = weakMgr;
//                                 [strongMgr.m_oAudioPlayer stopPlay];
//                             }];
//}
//
//#pragma mark - Audio Actions
//- (void)onStartRecord:(id)sender {
//
//    __weak typeof(self)weakSelf = self;
//    void(^recordAction)(void) = ^(void) {
//        __strong __typeof(weakSelf)strongSelf = weakSelf;
//
//        UIButton *btn = strongSelf.m_helperView.m_voiceAttachView.m_addButton;
//        if (btn.tracking && btn.touchInside) {
//            strongSelf.m_recordView.hidden = NO;
//            [strongSelf StartRecording];
//
//        }
//    };
//
//    [IBTAudioRecorder checkMicrophonePermissionAndRunAction:recordAction];
//}
//
//- (void)onEndRecord:(id)sender {
//    _m_recordView.hidden = YES;
//    [self StopRecording];
//}
//
//- (void)OnAudioEndRecord {
//    _m_recordView.hidden = YES;
//}
//
//- (void)UpdateRecordPower:(float)power {
//
//    if (_m_recordView.hidden) {
//        return;
//    }
//
//    // 10^-160  ~  10^0
//    NSUInteger waveLevel = 1;
//    if (power < (1.0f/4.0f)) {
//        waveLevel = 1;
//    }
//    else if (power < (2.0f/4.0f)) {
//        waveLevel = 2;
//    }
//    else if (power < (3.0f/4.0f)) {
//        waveLevel = 3;
//    }
//    else {
//        waveLevel = 4;
//    }
//    
//    [_m_recordView updateWithWavePower:waveLevel];
//}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}



@end
