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

#import "ICRQuestionBaseViewController.h"

#import "ICRQuestionManager.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"

#import "ICRQSingleSelectViewController.h"
#import "ICRQMutiSelectViewController.h"
#import "ICRQAViewController.h"
#import "ICRQScoreViewController.h"
#import "ICRQStoreStudyViewController.h"
#import "ICRQReseachViewController.h"
#import "ICRQStarViewController.h"
#import "ICRSingleScoreViewController.h"

#import "ICRPatrolResultViewController.h"
#import "GTOPatrolPlan.h"
//#import "ICRTaskEditViewController.h"

#define F_GAP   (5)
#define SELECT_PAGE 100
const CGFloat m_fMaxAudioRecoderDuration = 58;
const CGFloat m_fMinAudioRecoderDuration = 1;

@interface ICRQuestionBaseViewController ()
<
IBTImagePickerDelegate,
// ICRTaskEditViewDelegate,
UITextFieldDelegate,
ICRAttachmentViewDelegate
>
{
    BOOL m_bIsLoaded;
    
}
typedef NS_ENUM(NSUInteger,alertViewTag) {
    kAlertViewPageTag = 0,
    kAlertViewDeleteTag
};
@property (nonatomic, strong) JTRecordView *m_recordView;
@property (strong,nonatomic) UIView *alertView;
@property (strong,nonatomic) UIView *alertInfo;
@property (strong,nonatomic) UITextField *pageTextF;
@property (nonatomic, assign) NSInteger m_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 ICRQuestionBaseViewController

#pragma mark - Life Cycle

- (instancetype)initWithQuestion:(GTOQuestion *)question
                          answer:(ICRAnswer *)answer
{
    
    switch (question.type) {
        case kICRQestionTypeSingleSel://0
            self = [[ICRQSingleSelectViewController alloc] init];
            break;
        case kICRQestionTypeMultipleSel://1
            self = [[ICRQMutiSelectViewController alloc] init];
            break;
        case kICRQestionTypeReply://2  回复类
            self = [[ICRQAViewController alloc] init];
            break;
        case kICRQestionTypeScore://3  评分类
            self = [[ICRQScoreViewController alloc] init];
            break;
        case kICRQestionTypeStoreInv://4 库存调查类
            self = [[ICRQStoreStudyViewController alloc] init];
            break;
        case kICRQestionTypeSpeciesInv://5 品类调查类
            self = [[ICRQReseachViewController alloc] init];
            break;
        case kICRQestionTypeStarNum://6  星数类
            self = [[ICRQStarViewController alloc] init];
            break;
        case kICRQestionTypeSingleScore://7
            self = [[ICRSingleScoreViewController alloc] init];
            break;
        default:
            // self = [[ICRQSingleSelectViewController alloc] init];
            self = [super init];
            break;
    }
    
    if (!self) {
        return nil;
    }
    
    self.m_question = question;
    self.m_answer = answer;
    
    [self setupDefaultAnswer];
    
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    UIBarButtonItem *rightBtnItem = [[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"search"] style:UIBarButtonItemStylePlain target:self action:@selector(selectProblem)];
    // rightBtnItem.title = @"选择跳转题目";
    self.navigationItem.rightBarButtonItem = rightBtnItem;
    
    //问题明细 QuestionDetail
    NSSortDescriptor *sort = [NSSortDescriptor sortDescriptorWithKey:@"index" ascending:YES];
    self.m_arrOptions = [self.m_question.details sortedArrayUsingDescriptors:@[sort]];//seq:库存或调研题的序号
    
    [self setupSubviews];
    [self p_loadPhotos];
    [self registerForKVO];
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];

    if (!m_bIsLoaded) {
        m_bIsLoaded = YES;
        if (_m_answer.photo) {
            ICRPostAttachment *pPic = [ICRPostAttachment DBObject];
            [pPic praseFromJsonDict:_m_answer.photo];
            
            NSData *imageData = [NSData dataFromBase64String:pPic.content];
            UIImage *image = [UIImage imageWithData:imageData];
            
            [self addAttachment:image];
        }
        
        if (_m_answer.task) {
            ICRPostTask *pTask = [ICRPostTask DBObject];
            [pTask praseFromLocalDict:_m_answer.task];
            
            [self addAttachment:pTask];
        }
        
        if (_m_answer.voice) {
            ICRPostAttachment *pVoice = [ICRPostAttachment DBObject];
            [pVoice praseFromJsonDict:_m_answer.voice];
            
            NSData *voiceData = [NSData dataFromBase64String:pVoice.content];
            
            [self addAttachment:voiceData];
        }
        
    }
}


- (void)p_loadPhotos {

    //显示后台上面的附件 网络上获取附件
    if (_m_answer.resultAttachments.count > 0) {
        for(NSDictionary *dict in _m_answer.resultAttachments){
            ICRPostAttachment *postAttachment = [ICRPostAttachment DBObject];
            [postAttachment praseFromJsonDict:dict];
            self.d_isDownLoadImg = YES;
            [self addAttachment:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",HTTP_LOCAL_BASE_URL ,postAttachment.fileUrl]]];
        }
        return;
    } else{
        //加载本地图片
        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,_m_answer.questionUuid,_m_answer.plan_uuid,_m_answer.store_uuid];
        };
        
        __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];
                        }
                        
                    }
                }
            }
        };
        
        ICRDataBaseController *dbCtl = [ICRDataBaseController sharedController];
        [dbCtl runFetchForClass:[ICRPostAttachment class]
                     fetchBlock:fetchBlk
              fetchResultsBlock:fetchResultBlk];

        
        
        if (_m_answer.task) {
            ICRPostTask *pTask = [ICRPostTask DBObject];
            [pTask praseFromLocalDict:_m_answer.task];
            
            [self addAttachment:pTask];
        }
        
        if (_m_answer.voice) {
            ICRPostAttachment *pVoice = [ICRPostAttachment DBObject];
            [pVoice praseFromJsonDict:_m_answer.voice];
            
            NSData *voiceData = [NSData dataFromBase64String:pVoice.content];
            
            [self addAttachment:voiceData];
        }
        
    }
    
}


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


//重写 父类：IBTUIViewController中的左边按钮的方法
- (void)disMissSelf {  //每次退出时写到数据库中  dismissView
    [super disMissSelf];
    if(!self.m_answer.bIsAnswered) {
        [super disMissSelf];
        return;
    }
    [_m_answer saveToDBWithHandleData:NULL complete:^{
        [IBTLoadingView hideHUDWithText:nil];
        [super disMissSelf];
        
    } fail:^(NSError *error) {
        
        [IBTLoadingView hideHUDWithText:error.localizedDescription];
    }];
}

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

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

- (void)initScrollViewWithRect:(CGRect)rect {
    IBTUIScrollView *scrollV = [[IBTUIScrollView alloc] initWithFrame:rect];
    scrollV.bHandleKeyboard = YES;
    self.m_contentScrollView = scrollV;
}

- (void)openEditTaskView:(ICRTask *)task
{
    //    ICRQuestionManager *mgr = [ICRQuestionManager sharedManager];
    //
    //    ICRTaskEditViewController *tVC =
    //    [[ICRTaskEditViewController alloc] initWithTask:task store:mgr.m_store];
    //    tVC.m_delegate = self;
    //    [self PushViewController:tVC animated:YES];
}

- (void)addAttachment:(id)oAtt { //
    
    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.m_helperView.m_photoAttachView;
    } else {
        iconImg = oAtt;
        selector = @selector(onTapImageView:);
        attachView = self.m_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(_d_isDownLoadImg) {
        attachView.isDownImg = YES;
        attV.m_imageView.backgroundColor = [UIColor grayColor];
        if (!self.d_notEdit) {
            [attV updateWithType:kATTCloseBtn masker:nil placeHolder:nil image:iconImg title:nil];
        } else {
            [attV updateWithType:kATTNormal masker:nil placeHolder:nil image:iconImg title:nil];
        }
        
    } else {
        
        if (!self.d_notEdit) {
            [attV updateWithType:kATTCloseBtn masker:nil placeHolder:nil image:iconImg title:nil];
        } else {
            [attV updateWithType:kATTNormal masker:nil placeHolder:nil image:iconImg title:nil];
        };
    }
    
    
    attV.m_oAttachmentWrap = oAtt;
    
    [attV addTarget:self
             action:selector
   forControlEvents:UIControlEventTouchUpInside];
    
    [attachView addContentAttachmentView:attV];
}
#pragma ICRAttachmentViewDelegate
- (void)attachmentView:(ICRAttachmentView *)attachmentView removeContentAttachmentViewAtIndex:(NSUInteger)uiIndex {
    
//    UIAlertView *alertV =[ [UIAlertView alloc]initWithTitle:@"是否删除图片" message:@"" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
//    self.d_removeIndex = uiIndex;
//    alertV.tag = kAlertViewDeleteTag;
//    [alertV show];
    
    ICRPostAttachment *postAttachment = _d_muArrPhotos[uiIndex];
    ICRDataBaseController *dataBaseC = [ICRDataBaseController sharedController];
    [dataBaseC.m_dbQueue inDatabase:^(FMDatabase *db) {
        NSString *sql = [NSString stringWithFormat:@"DELETE FROM %@ WHERE fileName = ?",[ICRPostAttachment TableName]];
        [db executeUpdate:sql,postAttachment.fileName];
    }];
    [self.d_muArrPhotos removeObjectAtIndex:uiIndex];
    
}
- (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 fileName = ?",[ICRPostAttachment TableName]];
//        [db executeUpdate:sql,postAttachment.fileName];
//    }];
//    [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 - Action
- (void)onShowImagePicker:(__unused id)sender {
    [[ICRQuestionManager 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)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.m_answer.bIsAnswered) {
        [super disMissSelf];
        return;
    }
    [self.m_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]);
    //    ICRQuestionManager *mgr = [ICRQuestionManager sharedManager];
    //    UIViewController *qVC = [mgr questionViewControlAtIndex:indexProblem - 1];
    //    if (qVC) {
    //
    //        [self PresentModalViewController:qVC animated:YES];
    //       // [self PushViewController:qVC animated:YES];
    //    }
    //    else {
    //        [self openResultView];
    //    }
    //    [[NSNotificationCenter defaultCenter] postNotificationName:KNOTIFICATION_QUESTION_SELECTED object:nil];
    //
    //    [self creatAlphaView];
    //    [self creatAlterInfo];
}
- (void)onNextBtnAction:(__unused id)sender {
    if(!self.m_answer.bIsAnswered) {
        [super disMissSelf];
        return;
    }
    [_m_answer saveToDBWithHandleData:NULL
                             complete:^{
                                 [IBTLoadingView hideHUDWithText:nil];
                                 [super disMissSelf];
                                 // [ICRQuestionManager sharedManager].m_patrolPlan = nil;
                                 
                             }
                                 fail:^(NSError *error) {
                                     
                                     [IBTLoadingView hideHUDWithText:error.localizedDescription];
                                 }];
    
    //    ICRQuestionManager *mgr = [ICRQuestionManager sharedManager];
    //    UIViewController *qVC = [mgr questionViewControlAtIndex:self.m_uiIndex + 1];
    //    if (qVC) {
    //        [self PushViewController:qVC animated:YES];
    //    }
    //    else {
    //        // TODO
    //    }
}
- (void)onBeforeBtnAction: (__unused id)sender {
    [self PopViewControllerAnimated:YES];
    //    ICRQuestionManager *mgr = [ICRQuestionManager sharedManager];
    //    UIViewController *qVC = [mgr questionViewControlAtIndex:self.m_uiIndex - 1];
    //    if (self.m_uiIndex) {
    //        [self PushViewController:qVC animated:YES];
    //    }
    //    else {
    //        [self popoverPresentationController];
    //    }
}
- (void)onLastBtnAction: (__unused id)sender {
    // TODO
}

- (void)tap:(UIGestureRecognizer *)recognizer{
    // TODO
}
- (void)creatAlphaView{
    //UIViewController
    
    //_alertView = [[UIView alloc]initWithFrame:self.view.bounds];
    _alertView = [[UIView alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    _alertView.backgroundColor = [UIColor clearColor];
    [[UIApplication sharedApplication].keyWindow addSubview:_alertView];
    
    UIView *alphaView = [[UIView alloc]initWithFrame:_alertView.frame];
    alphaView.backgroundColor = [UIColor blackColor];
    alphaView.alpha = 0.3;
    [_alertView addSubview: alphaView];
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tap:)];
    [tap setDelegate:(id<UIGestureRecognizerDelegate>)self];
    tap.numberOfTouchesRequired = 1;
    tap.numberOfTapsRequired = 1;
    [_alertView setTag:10000];
    [_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 (!_alertInfo) {
        _alertInfo = [[UIView alloc]initWithFrame:CGRectMake(0,alertInfoY,alertInfoW,alertInfoH)];
        [_alertInfo setBackgroundColor:[UIColor clearColor]];
        [_alertView  addSubview:_alertInfo];
        
        UIView *info = [[UIView alloc]initWithFrame:CGRectMake(0, padding, alertInfoW, alertInfoH - 64)];
        info.backgroundColor = [UIColor whiteColor];
        [_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,[[ICRQuestionManager sharedManager] m_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.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 (_alertInfo) {
        [_alertInfo removeFromSuperview];
        _alertInfo = nil;
    }
    
    if (_alertView) {
        [_alertView removeFromSuperview];
        _alertView = nil;
    }
    
    
}
- (void)sureSelectionClicked:(UIButton *)btn {
    btn.tag = self.m_selectPage;
    ICRQuestionManager *mgr = [ICRQuestionManager 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 (_alertInfo) {
        [_alertInfo removeFromSuperview];
        _alertInfo = nil;
    }
    
    if (_alertView) {
        [_alertView removeFromSuperview];
        _alertView = nil;
    }
    
    if (self.m_uiIndex != 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:@"正在保存..."];
    
    ICRQuestionManager *mgr = [ICRQuestionManager sharedManager];
    
}

- (void)setupDefaultAnswer {
    if (!self.m_answer) {
        self.m_answer = [ICRAnswer DBObject];
        self.m_answer.content = @"";
    }
    ICRQuestionManager *mgr = [ICRQuestionManager sharedManager];
    self.m_answer.uuid = _m_question.uuid;
    self.m_answer.store_uuid = mgr.m_store_uuid;
    self.m_answer.plan_uuid = mgr.m_plan_uuid;
    self.m_answer.questionUuid = _m_question.uuid;//问题的id
    self.m_answer.type = _m_question.type;
    self.m_answer.category = _m_question.category;
}

#pragma mark - UITextFieldDelegate
- (void)textFieldDidEndEditing:(UITextField *)textField {
    if (textField.tag == SELECT_PAGE) {
        self.m_selectPage = [textField.text integerValue];
    }
    
}
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    //    if (self.m_question.type == kICRQestionTypeReply) {
    //        self.m_answer.content = self.m_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];
    attE.entityType = GTO_ENTITYTYPE_PATROL_ANSWER;
    attE.store_uuid = _m_answer.store_uuid;
    attE.plan_uuid = _m_answer.plan_uuid;
    
    attE.questionUuid = _m_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];
    if (!self.d_postAttachment) {
        self.d_postAttachment = attE;
        self.d_postAttachment.entityUuid = [[ICRUserUtil sharedInstance] mobileID];
    }
    attE.entityUuid = self.d_postAttachment.entityUuid;
    if (!self.d_muArrPhotos) {
        self.d_muArrPhotos = [NSMutableArray array];
    }
    
    [attE saveToDBWithHandleData:NULL complete:NULL fail:NULL];
    if(!_m_answer.resultAttachmentId) {
        self.m_answer.resultAttachmentId = self.d_postAttachment.entityUuid;
        [self.m_answer saveToDBWithHandleData:NULL complete:NULL fail:NULL];
    }
    [self.d_muArrPhotos addObject:attE];
    
    [self addAttachment:image];
    
}

- (void)imagePicker:(IBTImagePickerController *)picker
didVideoPickedWithURL:(NSURL *)videoUrl {
    
}

#pragma mark - KVO

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

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

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

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
    [self.m_contentScrollView setContentInsetTop:0 andBottom:self.view.height - _m_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 ([_m_helperView.m_inputTxtF isFirstResponder]) {
        _m_helperView.y = self.view.height - CGRectGetHeight(keyboardBounds) - 75;
    }
    
    // commit animations
    [UIView commitAnimations];
}

- (void)keyboardWillHide:(NSNotification *)note {
    //[_pageTextF resignFirstResponder];
    [self textFieldDidEndEditing:_pageTextF];
    //    if (self.m_question.type == kICRQestionTypeReply) {
    //        self.m_answer.content = self.m_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
    _m_helperView.y = self.view.height - _m_helperView.height;
    
    // commit animations
    [UIView commitAnimations];
}

#pragma mark - Audio

- (void)StartRecording {
    
    ICRQuestionManager *qMgr = [ICRQuestionManager 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];
}

@end
