ICRQResultViewController.m 16.1 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491
//
//  ICRQResultViewController.m
//  XFFruit
//
//  Created by Xummer on 15/6/10.
//  Copyright (c) 2015年 Xummer. All rights reserved.
//

#import "ICRQResultViewController.h"
#import "ICRQuestionHelperView.h"
#import "ICRPatrolResultViewController.h"
#import "ICRAttachmentView.h"

#import "ICRPatrolPlan.h"
#import "ICRAnswer.h"
#import "ICRStoreResult.h"
#import "ICRQuestion.h"
#import "ICRTask.h"
#import "ICRPostTask.h"
#import "ICRQuestionManager.h"

#import "ICRTaskEditViewController.h"

@interface ICRQResultViewController () <UITextFieldDelegate, ICRTaskEditViewDelegate>

@property (strong, nonatomic) IBTTableViewInfo *m_tableViewInfo;
@property (strong, nonatomic) ICRQuestionHelperView *m_helperView;

@property (strong, nonatomic) ICRPatrolPlan *m_plan;
@property (assign, nonatomic) NSUInteger m_storeID;
@property (strong, nonatomic) ICRStoreResult *m_result;

@property (strong, nonatomic) NSArray *m_answers;

@end

@implementation ICRQResultViewController

#pragma mark - Life Cycle
- (instancetype)initWithPatrolPlan:(id)plan andStoreResult:(id)result {
    self = [super init];
    if (!self) {
        return nil;
    }
    
    if ([plan isKindOfClass:[ICRPatrolPlan class]]) {
        self.m_plan = plan;
    }
    
    if ([result isKindOfClass:[ICRStoreResult class]]) {
        
        ICRStoreResult *res = result;
        
        NSMutableArray *mArr = [NSMutableArray array];
        NSMutableArray *mArrAns = [NSMutableArray array];
        for (NSDictionary *dict in res.answers) {
            ICRAnswer *ans = [ICRAnswer DBObject];
            [ans praseFromLocalDict:dict];
            [mArr safeAddObject:ans];
            [mArrAns safeAddObject:[ans dictForCommit]];
        }
        self.m_answers = mArr;
        res.answers = mArrAns;
        self.m_result = res;
    }
    
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.title = @"巡店纪录";
    
    CGFloat fHeight = 210;
    self.m_helperView = [[ICRQuestionHelperView alloc] initWithFrame:(CGRect){
        .origin.x = 0,
        .origin.y = self.view.height - fHeight,
        .size.width = self.view.width,
        .size.height = fHeight
    } isResult:YES];
    _m_helperView.autoresizingMask = UIViewAutoresizingFlexibleTopMargin;
    [_m_helperView.m_taskAttachView.m_addButton addTarget:self
                                                    action:@selector(onShowTaskCreateView:)
                                          forControlEvents:UIControlEventTouchUpInside];
    _m_helperView.m_inputTxtF.delegate = self;
    _m_helperView.m_inputTxtF.text = _m_result.remark;
    
    [_m_helperView.m_nextBtn setTitle:@"提交处理" forState:UIControlStateNormal];
    [_m_helperView.m_nextBtn addTarget:self
                                action:@selector(onSubmitBtnAction:)
                      forControlEvents:UIControlEventTouchUpInside];
    
    [self initTableViewInfo];
    
    [self.view addSubview:_m_helperView];
    
    [self registerForKVO];
}

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

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

#pragma mark - Private Method

- (void)initTableViewInfo {
    
    self.view.backgroundColor = [UIColor colorWithR:240 g:246 b:255 a:1];

    self.m_tableViewInfo = [[IBTTableViewInfo alloc] initWithFrame:self.view.bounds
                                                             style:UITableViewStylePlain];
    
    IBTTableView *tableV = [_m_tableViewInfo getTableView];
    tableV.backgroundColor = [UIColor clearColor];
    tableV.bHandleKeyboard = YES;
    
    // Footer
    UIButton *btn = nil;
    UIView *tableFooter =
    [tableV buttonViewWithTitle:@"浏览巡店结果"
                          color:ICR_ORANGE_BTN_COLOR
                         topGap:25
                        pointer:&btn
                         target:self
                         action:@selector(oneRsultButtonAction:)];
    tableV.tableFooterView = tableFooter;
    
    
    [self.view addSubview:tableV];
    
    // # Section 0
    IBTTableViewSectionInfo *sec0Info = [IBTTableViewSectionInfo sectionInfoDefaut];
    
    // User ID
    IBTTableViewCellInfo *titleCellInfo =
    [IBTTableViewCellInfo normalCellForSel:nil target:nil
                                     title:[IBTCommon localizableString:@"Title"]
                                rightValue:_m_plan.name
                             accessoryType:UITableViewCellAccessoryNone];
    titleCellInfo.selectionStyle = UITableViewCellSelectionStyleNone;
    
    [sec0Info addCell:titleCellInfo];
    
    IBTTableViewCellInfo *typeCellInfo =
    [IBTTableViewCellInfo normalCellForSel:nil target:nil
                                     title:[IBTCommon localizableString:@"Type"]
                                rightValue:_m_plan.category
                             accessoryType:UITableViewCellAccessoryNone];
    typeCellInfo.selectionStyle = UITableViewCellSelectionStyleNone;
    
    [sec0Info addCell:typeCellInfo];
    
    NSString *nsStart = [[_m_plan.beginDate componentsSeparatedByString:@" "] firstObject];
    NSString *nsEnd = [[_m_plan.endDate componentsSeparatedByString:@" "] firstObject];
    
    IBTTableViewCellInfo *planTimeCellInfo =
    [IBTTableViewCellInfo normalCellForSel:nil target:nil
                                     title:[IBTCommon localizableString:@"Scheduled Time"]
                                rightValue:[NSString stringWithFormat:@"%@~%@", nsStart, nsEnd]
                             accessoryType:UITableViewCellAccessoryNone];
    planTimeCellInfo.selectionStyle = UITableViewCellSelectionStyleNone;
    
    [sec0Info addCell:planTimeCellInfo];
    
    IBTTableViewCellInfo *startTimeCellInfo =
    [IBTTableViewCellInfo normalCellForSel:nil target:nil
                                     title:[IBTCommon localizableString:@"Start Time"]
                                rightValue:_m_result.beginTime
                             accessoryType:UITableViewCellAccessoryNone];
    startTimeCellInfo.selectionStyle = UITableViewCellSelectionStyleNone;
    
    [sec0Info addCell:startTimeCellInfo];
    
    IBTTableViewCellInfo *endTimeCellInfo =
    [IBTTableViewCellInfo normalCellForSel:nil target:nil
                                     title:@"结束时间"
                                rightValue:_m_result.endTime
                             accessoryType:UITableViewCellAccessoryNone];
    endTimeCellInfo.selectionStyle = UITableViewCellSelectionStyleNone;
    
    [sec0Info addCell:endTimeCellInfo];
    
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    dateFormatter.locale = [[NSLocale alloc] initWithLocaleIdentifier:@"zh_CN"];
    [dateFormatter setDateFormat:@"yyy-MM-dd HH:mm:ss"];
    
    NSDate *startDate = [dateFormatter dateFromString:_m_result.beginTime];
    NSDate *endDate = [dateFormatter dateFromString:_m_result.endTime];
    
    NSTimeInterval costTime = [endDate timeIntervalSince1970] - [startDate timeIntervalSince1970];
    NSTimeInterval mins = costTime/60;
    
    NSUInteger h = mins / 60;
    NSUInteger m = mins - h * 60;
    
    NSString *nsCostTime;
    
    if (h > 0) {
        nsCostTime = [NSString stringWithFormat:@"%@小时%@分", @( h ), @( m )];
    }
    else {
        nsCostTime = [NSString stringWithFormat:@"%@分", @( m ? m : 1 )];
    }
    
    IBTTableViewCellInfo *costTimeCellInfo =
    [IBTTableViewCellInfo normalCellForSel:nil target:nil
                                     title:@"耗时"
                                rightValue:nsCostTime
                             accessoryType:UITableViewCellAccessoryNone];
    endTimeCellInfo.selectionStyle = UITableViewCellSelectionStyleNone;
    
    [sec0Info addCell:costTimeCellInfo];
    
    [_m_tableViewInfo addSection:sec0Info];
    
}

- (void)uploadTaskAndAttachesWithComplete:(void (^)(void))complete {
    
    NSMutableArray *arrTasks = [NSMutableArray array];
    NSMutableArray *arrAttachs = [NSMutableArray array];
    
    // Result Task
    if ([_m_helperView.m_taskAttachView.m_arrAttViews count] > 0) {
        ICRAttachmentUnit *unit = [_m_helperView.m_taskAttachView.m_arrAttViews firstObject];
        ICRPostTask *pTask = unit.m_oAttachmentWrap;
        
        [arrTasks safeAddObject:[pTask dictForCommit]];
    }
    
    // Answers
    for (ICRAnswer *answer in _m_answers) {
        if (answer.task) {
            ICRPostTask *postTask = [ICRPostTask DBObject];
            [postTask praseFromLocalDict:answer.task];
            
//            [arrAttachs safeAddObject:postTask.photo];
            
            [arrTasks safeAddObject:[postTask dictForCommit]];
        }
        
        [arrAttachs safeAddObject:answer.photo];
        [arrAttachs safeAddObject:answer.voice];
    }
    
    if ([arrAttachs count] == 0 && [arrTasks count] == 0) {
        if (complete) {
            complete();
        }
        
        return;
    }
    
    __block NSUInteger uiTaskCompleteCount = 0;
    __block NSUInteger uiAttachCompleteCount = 0;
    NSUInteger uiAllTaskCount = [arrTasks count];
    NSUInteger uiAllAttachCount = [arrAttachs count];
    
    ICRHTTPController *httpCtrl = [ICRHTTPController sharedController];
    
    void(^taskSucc)(id) = ^(id data) {
        uiTaskCompleteCount ++;
        
        if (uiTaskCompleteCount == uiAllTaskCount &&
            uiAttachCompleteCount == uiAllAttachCount)
        {
            if (complete) {
                complete();
            }
        }
    };
    
    void(^taskFail)(id) = ^(id data) {
        uiTaskCompleteCount ++;
        
        if (uiTaskCompleteCount == uiAllTaskCount &&
            uiAttachCompleteCount == uiAllAttachCount)
        {
            if (complete) {
                complete();
            }
        }
    };
    
    void(^attSucc)(id) = ^(id data) {
        uiAttachCompleteCount ++;
        
        if (uiTaskCompleteCount == uiAllTaskCount &&
            uiAttachCompleteCount == uiAllAttachCount)
        {
            if (complete) {
                complete();
            }
        }
    };
    
    void(^attFail)(id) = ^(id data) {
        uiAttachCompleteCount ++;
        
        if (uiTaskCompleteCount == uiAllTaskCount &&
            uiAttachCompleteCount == uiAllAttachCount)
        {
            if (complete) {
                complete();
            }
        }
    };
    
    for (NSDictionary *dict in arrTasks) {
        [httpCtrl doCreateNewTaskWithInfo:dict success:taskSucc failure:taskFail];
    }
    
    for (NSDictionary *dict in arrAttachs) {
        [httpCtrl doAddAttachment:dict success:attSucc failure:attFail];
    }
}

#pragma mark - Actions
- (void)oneRsultButtonAction:(__unused id)sender {
    ICRPatrolResultViewController *rVC = [[ICRPatrolResultViewController alloc] initWithPatrolPlan:_m_plan andStoreResult:_m_result];
    [self PushViewController:rVC animated:YES];
}

- (void)onSubmitBtnAction:(__unused id)sender {
    
    ICRHTTPController *httpCtrl = [ICRHTTPController sharedController];
    
    [_m_helperView.m_inputTxtF resignFirstResponder];
    _m_result.remark = _m_helperView.m_inputTxtF.text ? : @"";
    __weak typeof(self)weakSelf = self;
    void(^succ)(id) = ^(id data) {
        __strong __typeof(weakSelf)strongSelf = weakSelf;
        [strongSelf uploadTaskAndAttachesWithComplete:^{
            UIViewController *pvc = self.navigationController.presentingViewController;
            ICRAppViewControllerManager *appVCtrl = [ICRAppViewControllerManager getAppViewControllerManager];
            UIViewController *VC = [appVCtrl getTabBarBaseViewController:[appVCtrl getCurTabBarIndex]];
            [VC PopViewControllerAnimated:NO];
            [pvc dismissViewControllerAnimated:YES completion:NULL];
        }];
    };
    
    void(^fail)(id) = ^(id data) {
        [IBTLoadingView showTips:data];
        _m_result.isNotUploaded = YES;
        
        [_m_result saveToDBWithHandleData:NULL complete:NULL fail:NULL];
    };
    
    [httpCtrl doAnswerPatrolPlanWithID: _m_plan.pID infoData:[_m_result dictForCommit]
                               success:succ
                               failure:fail];
}

- (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)onShowTaskCreateView:(__unused id)sender {
    [self openEditTaskView:nil];
}

- (void)onTapTask:(ICRAttachmentUnit *)unit {
    ICRPostTask *pTask = unit.m_oAttachmentWrap;
    [self openEditTaskView:[ICRTask taskFromPostTask:pTask]];
}

- (void)addAttachment:(id)oAtt {
    
    SEL selector = NULL;
    
    UIImage *iconImg;
    ICRAttachmentView *attachView = nil;
    
    iconImg = [UIImage imageNamed:@"icon_task_default"];
    selector = @selector(onTapTask:);
    attachView = self.m_helperView.m_taskAttachView;
    
    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
    }];
    [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 - ICRTaskEditViewDelegate
- (void)taskEditViewCtrl:(ICRTaskEditViewController *)viewCtrl taskData:(id)taskData
{
    ICRPostTask *pTask = taskData;
//    pTask.patrolResult = _m_result.mobileId;
    
    [self addAttachment:pTask];
    
    [viewCtrl PopViewControllerAnimated:YES];
}

#pragma mark - UITextFieldDelegate
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    [textField resignFirstResponder];
    return YES;
}

#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_tableViewInfo getTableView] 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 {
    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];
}

@end