//
//  WMBaseListViewController.m
//  Gengmei
//
//  Created by Thierry on 3/5/15. Maintain by iOS Team Member.
//  Copyright (c) 2015 Wanmeichuangyi. All rights reserved.
//

#import "WMBaseListViewController.h"
#import <GMRefresh/GMRefreshFooter.h>
#import <GMRefresh/GMRefreshHeader.h>
#import <Masonry/Masonry.h>
@import GMHud;
#import <Availability.h>
#import "GMBaseUtil.h"

@interface WMBaseListViewController ()


@end

@implementation WMBaseListViewController
@synthesize table = _table;

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

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self addKVO];
    
    _table = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, 0) style:_tableStyle];
    _table.keyboardDismissMode = UIScrollViewKeyboardDismissModeOnDrag;
    _table.separatorStyle = UITableViewCellSeparatorStyleNone;
    _table.delegate = self;
    _table.dataSource = self;
    _table.rowHeight = UITableViewAutomaticDimension;
    _table.estimatedRowHeight = 80;
    _table.sectionHeaderHeight = UITableViewAutomaticDimension;
    _table.sectionFooterHeight = UITableViewAutomaticDimension;

    // 如果_cellIdentifier 能转成一个UITableViewCell class，才去注册，否则会有crash发生
    if ([NSClassFromString(_cellIdentifier) isSubclassOfClass:[UITableViewCell class]]) {
        [_table registerClass:NSClassFromString(_cellIdentifier) forCellReuseIdentifier:_cellIdentifier];
    }
    _table.backgroundColor = [UIColor clearColor];
    if(@available(iOS 11.0, *)) {
        _table.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    }
    [self.view addSubview:_table];
    [_table mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view.mas_left);
        make.right.equalTo(self.view.mas_right);
        if ([self.parentViewController isKindOfClass:[UINavigationController class]]) {
            make.top.mas_equalTo(OCNavigationBar.barHeight);
        } else {
            make.top.mas_equalTo(0);
        }
//        make.top.mas_equalTo(OCNavigationBar.barHeight);

        make.bottom.mas_equalTo(0);
    }];
    
    __weak __typeof(self)weakSelf = self;
    if (_needHeaderRefresh) {
        _table.mj_header = [GMRefreshHeader headerWithRefreshingBlock:^{
            [weakSelf headerRereshing];
        }];
    }
    if (_needFooterRefresh) {
        _table.mj_footer = [GMRefreshFooter footerWithRefreshingBlock:^{
            [weakSelf footerRereshing];
        }];
    }
    
    //获取数据
    if (_immediateLoad) {
        [self loadRemoteData];
    }
}

- (void)updateOtherUIData{
    _table.hidden = NO;
}

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

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

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

#pragma mark - TableView Delegate
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    //返回行数
    return [self.viewModel.dataArray count];
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [self performSelector:@selector(deselect:) withObject:tableView afterDelay:0.2f];
}

- (void)deselect:(UITableView *)tableView
{
    [tableView deselectRowAtIndexPath:[tableView indexPathForSelectedRow] animated:YES];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:_cellIdentifier forIndexPath:indexPath];
    [self configDataForCell:cell atIndexPath:indexPath];
    return cell;
}

- (void)configDataForCell:(id)cell atIndexPath:(NSIndexPath *)indexPath {
    
}

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

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

#pragma - mark View Model Handle
- (void)addKVO
{
    [self.viewModel addObserver:self forKeyPath:@"fetchDataSuccess" options:NSKeyValueObservingOptionNew context:NULL];
}

- (void)removeKVO{
    // 因为fetchDataSuccess是在viewDidLoad中监听的，所以需要一个判断
    if ([self isViewLoaded]) {
        [self.viewModel removeObserver:self forKeyPath:@"fetchDataSuccess"];
    }
}

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context{
    if ([keyPath isEqualToString:@"fetchDataSuccess"] && object == self.viewModel) {
        [self hideLoading];
        if ([[self.viewModel fetchDataSuccess] boolValue]) {
            if ([[self.viewModel dataArray] count] == 0) {
                [self showEmptyView:GMEmptyViewTypeEmpty];
            }else {
                [self hideEmptyView];
            }
        }else{
            [self showEmptyView:GMEmptyViewTypeException];
        }
        
        if (_table!=nil) {
            [_table reloadData];
            [_table.mj_header endRefreshing];
            [_table.mj_footer endRefreshing];
            
        }
        
        [self updateOtherUIData];
    }
}

- (void)dealloc{
    [self removeKVO];
   
}

- (void)showEmptyView:(GMEmptyViewType)type {
    [super showEmptyView:type];
    if (self.emptyView.superview != nil) {
        [self.emptyView mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.left.mas_equalTo(0);
            make.right.mas_equalTo(0);
            if (_table != nil) {
                make.top.equalTo(_table.mas_top);
            } else {
                make.top.mas_equalTo(0);
            }
            make.bottom.mas_equalTo(0);
        }];
    }
}

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


@end
