
//
//  VankeProjectSummaryModel.m
//  vanke
//
//  Created by xiaomi on 15/10/6.
//  Copyright © 2015年 gomore. All rights reserved.
//

#import "VankeProjectSummaryModel.h"
#import "VankeUtil.h"

#pragma mark -

@implementation VankeProjectSummaryModel

@synthesize salesDate = _salesDate;
@synthesize passengerDate = _passengerDate;
@synthesize trafficDate = _trafficDate;

-(ProjectSummaryResponse*) getServerResp {
    return (ProjectSummaryResponse*) self.serverResp;
}

-(void) reload {
    [VankeProjectSummaryAPI cancel];
    
    VankeProjectSummaryAPI *api = [VankeProjectSummaryAPI api];
    
    @weakify(api);
    @weakify(self);
    
    NSDateFormatter *df = [[NSDateFormatter alloc] init];
    [df setDateFormat:@"yyyy-MM-dd"];
    
    if ([VankeUtil isBlankString:self.salesDate]) {
        _salesDate = [self yesterday:df];
    }
    if ([VankeUtil isBlankString:self.passengerDate]) {
        _passengerDate = [self yesterday:df];
    }
    if ([VankeUtil isBlankString:self.trafficDate]) {
        _trafficDate = [self today:df];
    }
    
    // TODO for debug
//    _salesDate = @"2015-09-21";
//    _passengerDate = @"2015-09-21";
//    _trafficDate = @"2015-09-21";
    
    api.salesDate = _salesDate;
    api.passengerDate = _passengerDate;
    api.trafficDate = _trafficDate;
    
    // 清空结果
    self.serverResp = nil;
    
    api.whenSucceed = ^{
        @normalize(api);
        @normalize(self);
        
        if (api.sending) {
            [self sendUISignal:self.RELOADING];
        } else {
            if (api.succeed) {
                if (nil == api.serverResp) {
                    api.failed = YES;
                } else {
                    self.serverResp = api.serverResp;
                }
            }
            [self sendUISignal:self.RELOADED];
        }
    };
    api.whenFailed = ^{
        @normalize(api);
        @normalize(self);
        
        self.serverResp = [ProjectSummaryResponse initWith:NO message:nil == api.errorDesc? @"网络异常": api.errorDesc];
        [self sendUISignal:self.RELOADED];
    };
    [api send];
}

-(NSString*) yesterday: (NSDateFormatter*) df {
    NSDate * yesterday = [[NSDate alloc]initWithTimeIntervalSinceNow:-24*60*60];
    return [df stringFromDate:yesterday];
}

-(NSString*) today: (NSDateFormatter*) df {
    return [df stringFromDate:[NSDate date]];
}

@end
