ICRSyncViewController.m 12.5 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
//
//  ICRSyncViewController.m
//  XFFruit
//
//  Created by Xummer on 3/24/15.
//  Copyright (c) 2015 Xummer. All rights reserved.
//

#import "ICRSyncViewController.h"
#import "IBTTableView.h"
#import "IBTTableViewCell.h"
#import "ICRSyncCellContentView.h"
#import "ICRPostTask.h"
#import "ICRAnswer.h"
#import "ICRStoreResult.h"

#define TABLE_HEAD_VIEW_HEIGHT       (50)
#define TITLE_LABEL_LEFT_MARGIN      (10)
#define TITLE_LABEL_VERTICAL_MARGIN  (20)

static NSString *syncCellIdetifier = @"IBTTableViewCell";

@interface ICRSyncViewController ()
<
UITableViewDataSource,
UITableViewDelegate
>

@property (strong, nonatomic) IBTTableView *m_tableView;
@property (strong, nonatomic) UIButton *m_SyncButton;
@property (strong, nonatomic) NSArray *m_arrFunctionTitle;
@property (strong, nonatomic) NSArray *m_arrTasks;
@property (strong, nonatomic) NSArray *m_arrPatrolResults;

@end

#pragma mark - life style

@implementation ICRSyncViewController

- (void)viewDidLoad {
    [super viewDidLoad];
//    [self setupSubviews];
//    [self initData];
//    [self getUnuploadData];

    // Do any additional setup after loading the view.
    
    CGRect rect = CGRectMake(0, 200, self.view.width, 30);
    IBTUILabel *lbl = [[IBTUILabel alloc]initWithFrame:rect];
    lbl.text = @"哎呦,功能还没实现呢,下次再来看看吧。";
    lbl.textAlignment = NSTextAlignmentCenter;
    lbl.font = [UIFont systemFontOfSize:15];
    lbl.textColor = GXF_NAVIGAYION_COLOR;
    [self.view addSubview:lbl];
}

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

#pragma mark - Privite Method
- (void)setupSubviews {
    
    self.m_tableView = [[IBTTableView alloc] initWithFrame:self.view.bounds style:UITableViewStylePlain];
    [_m_tableView registerClass:[IBTTableViewCell class] forCellReuseIdentifier:syncCellIdetifier];
    _m_tableView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
    _m_tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    _m_tableView.delegate = self;
    _m_tableView.dataSource = self;
    [self.view addSubview:_m_tableView];
    
    CGRect frame = self.view.frame;
    frame.size.height = TABLE_HEAD_VIEW_HEIGHT;
    
    UIView *headView = [[UIView alloc] initWithFrame:frame];
    UILabel *titleLabel = [[UILabel alloc] initWithFrame:(CGRect){
        .origin.x = TITLE_LABEL_LEFT_MARGIN,
        .origin.y = TITLE_LABEL_VERTICAL_MARGIN,
        .size.width = headView.width - TITLE_LABEL_LEFT_MARGIN * 2,
        .size.height = 20
    }];
    titleLabel.text = [IBTCommon localizableString:@"To Upload Data"];
    titleLabel.font = [UIFont systemFontOfSize:15];
    [headView addSubview:titleLabel];
    
    _m_tableView.tableHeaderView = headView;
    
    UIButton *button = nil;
    UIView *tableFooter = [_m_tableView buttonViewWithTitle:[IBTCommon localizableString:@"Submit"]
                                                      color:ICR_ORANGE_BTN_COLOR
                                                     topGap:20
                                                    pointer:&button
                                                     target:self
                                                     action:@selector(onSubmitAction:)];
    _m_tableView.tableFooterView = tableFooter;
    self.m_SyncButton = button;
}

- (void)initData {
    self.m_arrFunctionTitle = @[[IBTCommon localizableString:@"Task Progressing"],
                                [IBTCommon localizableString:@"Patrol Result"],
                                [IBTCommon localizableString:@"SignIn Record"]];
}

- (void)getUnuploadData {
    
    ICRDataBaseController *dbCtrl = [ICRDataBaseController sharedController];

    __weak typeof(self)weakSelf = self;
    
    // Task
    ICRDatabaseFetchBlock fetchBlk = ^FMResultSet *(FMDatabase *db) {
        NSString * sql = [NSString stringWithFormat:@"SELECT * FROM %@ WHERE %@ = ?", [ICRPostTask TableName], @"isNotUploaded"];
        return [db executeQuery:sql,  @( YES )];
    };
    
    ICRDatabaseFetchResultsBlock fetchResultsBlk = ^(NSArray *fetchedObjects) {
        __strong __typeof(weakSelf)strongSelf = weakSelf;
        strongSelf.m_arrTasks = fetchedObjects;
        [strongSelf.m_tableView reloadData];
    };
    
    [dbCtrl runFetchForClass:[ICRPostTask class]
                  fetchBlock:fetchBlk
           fetchResultsBlock:fetchResultsBlk];
    
    // Patrol
    ICRDatabaseFetchBlock pfetchBlk = ^FMResultSet *(FMDatabase *db) {
        NSString * sql = [NSString stringWithFormat:@"SELECT * FROM %@ WHERE %@ = ?", [ICRStoreResult TableName], @"isNotUploaded"];
        return [db executeQuery:sql,  @( YES )];
    };
    
    ICRDatabaseFetchResultsBlock pfetchResultsBlk = ^(NSArray *fetchedObjects) {
        __strong __typeof(weakSelf)strongSelf = weakSelf;
        strongSelf.m_arrPatrolResults = fetchedObjects;
        [strongSelf.m_tableView reloadData];
    };
    
    [dbCtrl runFetchForClass:[ICRStoreResult class]
                  fetchBlock:pfetchBlk
           fetchResultsBlock:pfetchResultsBlk];
}

#pragma mark - Actions

- (void)onSubmitAction:(id)sender {
    
    NSUInteger uiTasksCount = [_m_arrTasks count];
    NSUInteger uiResultCount = [_m_arrPatrolResults count];
    
    if (uiTasksCount == 0 &&
        uiResultCount == 0) {
        return;
    }
    
    __block NSUInteger uiTaskComleteCount = 0;
    __block NSUInteger uiResultComleteCount = 0;
    
    __weak typeof(self)weakSelf = self;
    void(^taskComplete)(void) = ^(void) {
        __strong __typeof(weakSelf)strongSelf = weakSelf;
        uiTaskComleteCount ++;
        
        if (uiTaskComleteCount == uiTasksCount &&
            uiResultComleteCount == uiResultCount) {
            [strongSelf getUnuploadData];
        }
    };
    
    void(^patrolComplete)(void) = ^(void) {
        __strong __typeof(weakSelf)strongSelf = weakSelf;

        uiResultComleteCount ++;
        
        if (uiTaskComleteCount == uiTasksCount &&
            uiResultComleteCount == uiResultCount) {
            [strongSelf getUnuploadData];
        }
    };
    
    for (ICRPostTask * task in _m_arrTasks) {
        [self updateTask:task complete:taskComplete];
    }
    
    for (ICRStoreResult * result in _m_arrPatrolResults) {
        [self updateResult:result complete:patrolComplete];
    }
}

#pragma mark - UITableViewDatasource

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 3;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:syncCellIdetifier];
    cell.userInteractionEnabled = NO;
    [self configueCell:cell forRowAtIndexPath:indexPath];
    
    return cell;
}

- (void)configueCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
    
    IBTTableViewCell *mCell = (IBTTableViewCell *)cell;
    UIView *view = mCell.contentView;
    
    ICRSyncCellContentView *contentView = [view viewWithClass:[ICRSyncCellContentView class]];
    
    if (!contentView) {
        
        contentView = [[ICRSyncCellContentView alloc] initWithFrame:view.bounds];
        [view addSubview:contentView];
        
    }
    
    NSUInteger uiCount = 0;
    switch (indexPath.row) {
        case 0:
            uiCount = [_m_arrTasks count];
            break;
        case 1:
            uiCount = [_m_arrPatrolResults count];
            break;
            
        default:
            break;
    }
    
    [contentView updateItemLabelTitle:[_m_arrFunctionTitle objectAtIndex:indexPath.row]
                       valueLabelText:@( uiCount )];
    
}

#pragma mark - Action

- (void)uploadTaskAndAttaches:(ICRStoreResult *)result complete:(void (^)(void))complete {
    
    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]];
    }
    
    res.answers = mArrAns;
    
    NSMutableArray *arrTasks = [NSMutableArray array];
    NSMutableArray *arrAttachs = [NSMutableArray array];
    
    // Answers
    for (ICRAnswer *answer in mArr) {
        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];
    }
}


- (void)updateResult:(ICRStoreResult *)result complete:(void (^)(void))complete {
    ICRHTTPController *httpCtrl = [ICRHTTPController sharedController];
    
    __weak typeof(self)weakSelf = self;
    void(^succ)(id) = ^(id data) {
        __strong __typeof(weakSelf)strongSelf = weakSelf;
        [strongSelf uploadTaskAndAttaches:result complete:complete];
    };
    
    void(^fail)(id) = ^(id data) {
        [IBTLoadingView showTips:data];
//        result.isNotUploaded = YES;
        
        [result saveToDBWithHandleData:NULL complete:complete fail:NULL];
    };
    
    [httpCtrl doAnswerPatrolPlanWithID:result.uuid infoData:[result dictForCommit]
                               success:succ
                               failure:fail];

}

- (void)doUploadAttachmentsToTask:(ICRPostTask *)task
                         complete:(void (^)(void))complete
{
//    if (!task.photo) {
//        if (complete) {
//            complete();
//        }
//        return;
//    }
//    
    void(^suc)(id) = ^(id data) {
        if (complete) {
            complete();
        }
    };
    
    void(^fai)(id) = ^(id data) {
//        [IBTLoadingView showTips:@"上传失败"];
    };
    
    ICRHTTPController *httpCtrl = [ICRHTTPController sharedController];
//    
//    [httpCtrl doAddAttachment:task.photo
//                      success:suc
//                      failure:fai];
}


- (void)updateTask:(ICRPostTask *)task complete:(void (^)(void))complete {
    __weak typeof(self)weakSelf = self;
    
    void(^succ)(id) = ^(id data) {
        __strong __typeof(weakSelf)strongSelf = weakSelf;
        [strongSelf doUploadAttachmentsToTask:task complete:complete];
    };
    
    void(^fail)(id) = ^(id data) {
        [IBTLoadingView showTips:data];
//        task.isNotUploaded = YES;
        
        [task saveToDBWithHandleData:NULL complete:complete fail:NULL];
    };
    
    ICRHTTPController *httpCtrl = [ICRHTTPController sharedController];
    [httpCtrl doCreateNewTaskWithInfo:[task dictForCommit] success:succ failure:fail];

}
@end