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

#import "VankeStatementListModel.h"

#undef	PER_PAGE
#define PER_PAGE	(10)

@implementation VankeStatementListModel

@synthesize settleEquals = _settleEquals;
@synthesize confirmed = _confirmed;
@synthesize projectsIn = _projectsIn;
@synthesize shopNameOrCodeLike = _shopNameOrCodeLike;
@synthesize shops = _shops;
@synthesize lastResp = _lastResp;

- (void)load
{
    self.autoSave = YES;
    self.autoLoad = YES;
    self.shops = [NSMutableArray array];
}

- (void)unload
{
    self.settleEquals = nil;
    self.confirmed = nil;
    self.projectsIn = nil;
    self.shopNameOrCodeLike = nil;
    self.shops = nil;
}

#pragma mark - paging query

- (void)firstPage
{
    [self gotoPage:1];
}

- (void)nextPage
{
    if ( self.shops.count )
    {
        [self gotoPage:(self.shops.count / PER_PAGE + 1)];
    }
}

- (void)gotoPage:(NSUInteger)page {
    [VankeSettlementListAPI cancel];
    
    VankeSettlementListAPI *api = [VankeSettlementListAPI api];
    
    @weakify(api);
    @weakify(self);
    
    api.settleEquals = self.settleEquals;
    api.confirmed = self.confirmed;
    api.projectsIn = self.projectsIn;
    api.shopNameOrCodeLike = self.shopNameOrCodeLike;
    
    api.whenUpdate = ^
    {
        @normalize(api);
        @normalize(self);
        
        if ( api.sending )
        {
            [self sendUISignal:self.RELOADING];
        }
        else
        {
            if ( api.succeed )
            {
                StatementListResponse *resp = (StatementListResponse*) api.serverResp;
                self.lastResp = resp;
                if ( nil == resp || nil == resp.records )
                {
                    api.failed = YES;
                }
                else
                {
                    if ( page <= 1 )
                    {
                        [self.shops removeAllObjects];
                        [self.shops addObjectsFromArray:resp.records];
                    }
                    else
                    {
                        [self.shops addObjectsFromArray:resp.records];
                        [self.shops unique:^NSComparisonResult(id left, id right) {
                            return [((StatementShop*)left).shopCode compare:((StatementShop*)right).shopCode];
                        }];
                    }
                    
                    self.more = [resp hasMore];
                    self.loaded = YES;
                }
            }
                        
            [self sendUISignal:self.RELOADED];
        }
    };
    
    [api send];
}

@end
