//
//  WMBaseCollectionController.m
//  Gengmei
//
//  Created by wangyang on 9/2/15.
//  Copyright (c) 2015 Wanmeichuangyi. All rights reserved.
//

#import "WMBaseCollectionController.h"
#import <GMRefresh/GMRefreshFooter.h>
#import <GMRefresh/GMRefreshHeader.h>
#import <Masonry/Masonry.h>
@import GMHud;

@interface WMBaseCollectionController ()

@end

@implementation WMBaseCollectionController
@synthesize viewModel = _viewModel;
@synthesize collectionView = _collectionView;
@synthesize collectionViewLayout = _collectionViewLayout;

- (void)initController{
    
    [super initController];
    self.viewModel = [[WMFetchDataViewModel alloc] init];
    _needHeaderRefresh = YES;
    _needFooterRefresh = YES;
    _immediateLoad = YES;
}


- (void)viewDidLoad{
    
    [super viewDidLoad];
    [self addKVO];

    [self.view addSubview:self.collectionView];
    [_collectionView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.view).insets(UIEdgeInsetsMake(64, 0, 0, 0));
    }];

    __weak __typeof(self)weakSelf = self;
    if (_needHeaderRefresh) {
        _collectionView.mj_header = [GMRefreshHeader headerWithRefreshingBlock:^{
            [weakSelf headerRereshing];
        }];
    }
    if (_needFooterRefresh) {
        _collectionView.mj_footer = [GMRefreshFooter footerWithRefreshingBlock:^{
            [weakSelf footerRereshing];
        }];
    }

    //获取数据
    if (_immediateLoad) {
        [self loadRemoteData];
    }
}

- (void)hideNavigationBar {
    self.navigationBar.hidden = YES;
    [_collectionView mas_updateConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(0);
    }];
}


- (void)addKVO
{
    [self.viewModel addObserver:self forKeyPath:@"fetchDataSuccess" options:NSKeyValueObservingOptionNew context:NULL];
}
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context{
    if ([keyPath isEqualToString:@"fetchDataSuccess"] && object == self.viewModel) {
        [self hideLoading];
        _collectionView.hidden = NO;
        if ([[self.viewModel fetchDataSuccess] boolValue]) {
            if ([[self.viewModel dataArray] count] == 0 && [self.viewModel fetchDataNilMsg]) {
                [self showEmptyView:GMEmptyViewTypeEmpty];
            } else {
                [self hideEmptyView];
            }
            
        }else{
            [self showEmptyView:GMEmptyViewTypeException];
        }

        // 调用reloadData，并不会立即执行，而是下更新周期来了之后才可以。
        // 将 endRefreshing 与 endRefreshing 放到后面的好处就是此时可以利用 updateOtherUIData 做点额外的事。比如判断mj_header.isRefreshing
        [self updateOtherUIData];
        if (_collectionView) {
            [_collectionView reloadData];
            [_collectionView.mj_header endRefreshing];
            [_collectionView.mj_footer endRefreshing];
        }
    }
}

- (void)dealloc{
    [self removeKVO];

    if (self.isViewLoaded) {
        [self.viewModel removeObserver:self forKeyPath:@"fetchDataSuccess"];
    }
}

- (void)removeKVO{

}
/**
 *  @brief  下拉刷新
 */
- (void)headerRereshing
{
    [self.viewModel handleHeaderRefreshing];
}

/**
 *  @brief  上拉加载更多
 */
- (void)footerRereshing
{
    [self.viewModel handleFooterRereshing];
}


- (void)updateOtherUIData{
    
    // 如果 contentSize 高没有 _collectionView.bounds.size.height 这个大，就强制设置一下，这样 collectionView 还能下拉滑动，以保证上拉、下拉正常使用
    if (_collectionView.contentSize.height <= _collectionView.bounds.size.height) {
        _collectionView.contentSize = CGSizeMake(_collectionView.bounds.size.width, _collectionView.bounds.size.height);
    }
}

- (void)refreshList{
    
    [self.viewModel setStartNum:0];
    [[self.viewModel dataArray] removeAllObjects];
    [_collectionView reloadData];

    [self loadRemoteData];
}

- (void)loadRemoteData {
    [self showLoading:nil];
    [self.viewModel fetchRemoteData];
}

- (void)didMoveToParentViewController:(UIViewController *)parent {
    [super didMoveToParentViewController:parent];
    if (parent != nil && ![parent isKindOfClass:[UINavigationController class]]) {
        [_collectionView mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.edges.equalTo(self.view).insets(UIEdgeInsetsMake(0, 0, 0, 0));
        }];
    }
}

#pragma mark - UICollectionViewDelegate and UICollectionViewDataSource

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return self.viewModel.dataArray.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    return nil;
}


#pragma mark - Setter and Getter

- (UICollectionView *)collectionView{
    
    if (!_collectionView) {
        _collectionView = [[UICollectionView alloc] initWithFrame:self.view.bounds collectionViewLayout:self.collectionViewLayout];
        _collectionView.backgroundColor = [UIColor whiteColor];
        _collectionView.delegate = self;
        _collectionView.alwaysBounceVertical = YES;
        _collectionView.dataSource = self;
        _collectionView.hidden = YES;
    }
    return _collectionView;
}

- (UICollectionViewLayout *)collectionViewLayout{
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    layout.minimumLineSpacing = 3;
    layout.minimumInteritemSpacing = 3;
    layout.itemSize = CGSizeMake(50, 50);
    
    _collectionViewLayout = layout;
    return _collectionViewLayout;
}

#pragma mark - OCEmptyViewDelegate
- (void)emptyViewDidClickReload{
    [self loadRemoteData];
}

@end
