//
//  ALRankListViewController.m
//  GMAlpha
//
//  Created by Mikasa on 2018/11/8.
//  Copyright © 2018 Gengmei. All rights reserved.
//

#import "ALRankListViewController.h"
#import "ALRankListContainerViewController.h"
#import "ALRankContainerViewController.h"
#import "ALRankSearchViewController.h"
#import "GMTabBarController.h"
#import "ALRankListCell.h"
#import "ALRankSearchButton.h"
#import "ALNavSearchBarView.h"

#import <GMRefresh/GMRefreshFooter.h>
#import <GMRefresh/GMRefreshHeader.h>

@interface ALRankListViewController ()<UITableViewDataSource, UITableViewDelegate>

@property (nonatomic, strong) ALRankSearchButton *searchButton;
@property (nonatomic, strong) GMTableView *table;
@end

@implementation ALRankListViewController

- (ALRankSearchButton *)searchButton {
    if (!_searchButton) {
        ALRankSearchButton *searchButton = [[ALRankSearchButton alloc] initWithFrame:CGRectMake(15, 15, MAINSCREEN_WIDTH - 30, 33)];
        [searchButton addTarget:self action:@selector(rankSearchButtonClick) forControlEvents:UIControlEventTouchUpInside];
        _searchButton = searchButton;
    }
    return _searchButton;
}

- (GMTableView *)table {
    if (!_table) {
        _table = [[GMTableView alloc] initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, 0) style:UITableViewStylePlain];
        _table.keyboardDismissMode = UIScrollViewKeyboardDismissModeOnDrag;
        _table.separatorStyle = UITableViewCellSeparatorStyleNone;
        _table.delegate = self;
        _table.dataSource = self;
        _table.rowHeight = UITableViewAutomaticDimension;
        _table.estimatedRowHeight = 80;
        _table.sectionHeaderHeight = UITableViewAutomaticDimension;
        _table.sectionFooterHeight = UITableViewAutomaticDimension;
        _table.backgroundColor = RGBCOLOR_HEX(0xF4F3F8);
        if(@available(iOS 11.0, *)) {
            _table.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
        }
        GMView *headerView = [[GMView alloc] initWithFrame:CGRectMake(0, 0, MAINSCREEN_WIDTH, 63)];
        headerView.backgroundColor = [UIColor whiteColor];
        [headerView addSubview:self.searchButton];
        _table.tableHeaderView = headerView;
    }
    if (!_table.superview) {
        [self.view addSubview:_table];
    }
    return _table;
}
#pragma mark - view lifeCycle
- (void)initController {
    [super initController];
    self.viewModel = [ALPickListViewModel new];
    self.viewModel.refreshData = NO;
}

- (void)viewWillAppear:(BOOL)animated {
    
    [super viewWillAppear:animated];
    
    if (self.viewModel.refreshData) {
        
        [self reloadRefreshData];
        
    } else {
        if (self.viewModel.userListObject.users.count > 0) {
            [self.table reloadData];
        } else {
            [self showEmptyView:GMEmptyViewTypeEmpty];
        }
    }
}

- (void)reloadRefreshData {
    
    self.viewModel.refreshData = NO;
    self.viewModel.page = 1;
    [GMHudModule showLoading:nil];
    [self getUserPickData];
}


- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = RGBCOLOR_HEX(0xF4F3F8);
    
    [self.table mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(0);
        make.left.right.mas_equalTo(0);
        make.bottom.mas_equalTo(-UIView.safeAreaInsetsBottom);
    }];
    [self.table registerCell:[ALRankListCell class]];
    __weak __typeof(self)weakSelf = self;

    _table.mj_header = [GMRefreshHeader headerWithRefreshingBlock:^{
        weakSelf.viewModel.page = 1;
        [weakSelf getUserPickData];
    }];
    
    _table.mj_footer = [GMRefreshFooter footerWithRefreshingBlock:^{
        weakSelf.viewModel.page++;
        [weakSelf getUserPickData];
    }];
}

- (void)getUserPickData {
    
    // 获取数据时候隐藏空页面
    [self hideEmptyView];
    
    [self.viewModel excuteUserPickList:^(id responseObject) {
        
        if (self.viewModel.userListObject.users.count > 0) {
            [self.table reloadData];
        } else {
            [self showEmptyView:GMEmptyViewTypeEmpty];
        }
        [self.table.mj_header endRefreshing];
        [self.table.mj_footer endRefreshing];
        
    } failBlock:^(NSString *message) {
        
        if (self.viewModel.page > 1) {
            self.viewModel.page--;
        }
        
        if (self.viewModel.userListObject.users.count == 0) {
            [self showEmptyView:GMEmptyViewTypeException];
        }
        [self.table.mj_header endRefreshing];
        [self.table.mj_footer endRefreshing];
    }];
}

#pragma mark - UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    return self.viewModel.userListObject.users.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    ALRankListCell *cell = [tableView dequeueCell:[ALRankListCell class] forIndexPath:indexPath];
    cell.cellType = ALUserCellTypeList;
    cell.userIndex = indexPath.row;
    cell.shareData = self.viewModel.shareObject;
    cell.userObject = self.viewModel.userListObject.users[indexPath.row];
    cell.pick_id = self.viewModel.pick_id;
    __weak __typeof(self)weakSelf = self;
    cell.pickUserBlock = ^(ALUserObject *userObject) {
        
        __block ALRankContainerViewController *rankCtrl = nil;
        [[AppDelegate navigation].viewControllers enumerateObjectsUsingBlock:^(__kindof UIViewController * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            if ([obj isKindOfClass:[ALRankContainerViewController class]]) {
                rankCtrl = ( ALRankContainerViewController *)obj;
                *stop = YES;
            }
        }];
        if (rankCtrl) {
            rankCtrl.viewModel.pick_id = weakSelf.viewModel.pick_id;
            rankCtrl.viewModel.pick_user_id = userObject.pick_user_id;
            rankCtrl.viewModel.refreshData = YES;
            [[AppDelegate navigation] popToViewController:rankCtrl animated:YES];
        } else {
            rankCtrl = (ALRankContainerViewController *)AppDelegate.tabBarController.selectedViewController;
            rankCtrl.viewModel.pick_id = weakSelf.viewModel.pick_id;
            rankCtrl.viewModel.pick_user_id = userObject.pick_user_id;
            rankCtrl.viewModel.refreshData = YES;
            [[AppDelegate navigation] popToRootViewControllerAnimated:YES];
        }
    };
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return kRankListCellH;
}

- (void)rankSearchButtonClick {
    ALRankSearchViewController *searchaCtrl = [ALRankSearchViewController new];
    searchaCtrl.viewModel.pick_id = self.viewModel.pick_id;
    [AppDelegate.navigation pushViewController:searchaCtrl animated:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
@end
