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

#import "VankeStatementListModel.h"

#undef	PAGE_SIZE
#define PAGE_SIZE	(20)

@implementation VankeStatementListModel

@synthesize settleEquals = _settleEquals;
@synthesize billState = _billState;
@synthesize projectsIn = _projectsIn;
@synthesize shopLike = _shopLike;
@synthesize shops = _shops;
@synthesize lastResp = _lastResp;

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

- (void)unload
{
    self.settleEquals = nil;
    self.billState = nil;
    self.projectsIn = nil;
    self.shopLike = nil;
    self.shops = nil;
}

#pragma mark - paging query

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

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

- (void)gotoPage:(NSUInteger)page {
    [VankeSettlementListAPI cancel];
    
    VankeSettlementListAPI *api = [VankeSettlementListAPI api];
    
    @weakify(api);
    @weakify(self);
    
    api.settleEquals = self.settleEquals;
    api.billState = self.billState;
    api.projectsIn = self.projectsIn;
    api.shopLike = self.shopLike;
    api.pageNumber = page;
    api.pageSize = PAGE_SIZE;
    
    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.data || nil == resp.data.records )
                {
                    api.failed = YES;
                }
                else
                {
                    if ( page <= 1 )
                    {
                        [self.shops removeAllObjects];
                        [self.shops addObjectsFromArray:resp.data.records];
                    }
                    else
                    {
                        [self.shops addObjectsFromArray:resp.data.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
