//
//  KWMBasePageVC.m
//  iForeseaLife
//
//  Created by kevin on 7/7/14.
//  Copyright (c) 2014 Kollway Mobile. All rights reserved.
//

#import "KWMBasePageVC.h"
#import "MJRefresh.h"
#import "UIColor+SAMAdditions.h"
#import "MMJRefreshNormalHeader.h"
#import "KWMLoadingHeader.h"


@implementation KWMBasePageVC{
    
    //view
    __weak UIView *weakEmptyView;
    BOOL isLoading;
}

- (NSMutableArray *)dataList {
    if(_dataList == nil){
        _dataList = [[NSMutableArray alloc] initWithCapacity:100];
    }
    return _dataList;
}

/**
 * 设置下拉,上拉刷新
 */
- (void)setupPullToRefresh {
    __weak UITableView *tableView = [self targetTableView];
    __weak KWMBasePageVC *weakSelf = self;
    
    KWMLoadingHeader *header = [KWMLoadingHeader headerWithRefreshingBlock:^{
//        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [weakSelf reLoadData];
//        });
    }];
//    header.lastUpdatedTimeLabel.hidden = YES;
//    header.stateLabel.hidden = YES;


   /*
    NSMutableArray *mrefreshingImages = [NSMutableArray array];
    for (NSUInteger i = 1; i<=31; i++) {
        UIImage *image = [UIImage imageNamed:[NSString stringWithFormat:@"loading%zd", i]];
        [mrefreshingImages addObject:image];
    }
    NSArray *refreshArray  = mrefreshingImages.copy;

    
    NSMutableArray *mrefreshingImages2 = [NSMutableArray array];
    for (NSUInteger i = 31; i>=1; i--) {
        UIImage *image = [UIImage imageNamed:[NSString stringWithFormat:@"loading%zd", i]];
        [mrefreshingImages2 addObject:image];
    }
    for (NSUInteger i = 1; i<=31; i++) {
        UIImage *image = [UIImage imageNamed:[NSString stringWithFormat:@"loading%zd", i]];
        [mrefreshingImages2 addObject:image];
    }
    
    NSArray *refreshArray2  = mrefreshingImages2.copy;
    */
    
//    // 设置普通状态的动画图片
//    NSMutableArray *mRefreshingImages2 = [NSMutableArray array];
//    [mRefreshingImages2 addObject:[UIImage imageNamed:@"loading31"]];
//    [header setImages:mRefreshingImages2 forState:MJRefreshStatePulling];
//    
//    // 设置即将刷新状态的动画图片(一松开就会刷新的状态)
//   
//    [header setImages:refreshArray forState:MJRefreshStateIdle];
//    
//    // 设置正在刷新状态的动画图片
//    
//    [header setImages:refreshArray2 duration:refreshArray2.count * 0.02 forState:MJRefreshStateRefreshing];
//
    
    tableView.mj_header = header;
    tableView.mj_header.automaticallyChangeAlpha = YES;
    tableView.mj_footer = [self createFooter];
}

- (MJRefreshAutoNormalFooter *)createFooter {
    __weak KWMBasePageVC *weakSelf = self;
    
    MJRefreshAutoNormalFooter *footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        // 完全不知道为什么要延时2秒  现在去掉完全是浪费时间
//        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [weakSelf loadData];
//        });
    }];
    [footer setTitle:NO_MORE_DATA forState:MJRefreshStateNoMoreData];
    footer.hidden = YES;
    return footer;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    UITableView *tbv = [self targetTableView];
    tbv.delegate = self;
    tbv.dataSource = self;
    
    self.hasNextPage = YES;
    self.totalCount = @0;
    self.pageSize = @0;
    self.currentPage = @0;
    [self setupPullToRefresh];
    [self reLoadData];
}

//移除footerview(主要是去掉当数据没有显示点击或上啦加载更多的文字)
- (void)removeFooterView {
    __weak UITableView *tableView = [self targetTableView];
    tableView.mj_footer = nil;
}

- (void)loadData {
    NSAssert(NO, @"子类必须重写该方法");
}


- (UITableView *)targetTableView {
    NSAssert(NO, @"子类必须重写该方法");
    return nil;
}


- (void)reLoadData {
    if ([self isLoading]) {
        return;
    }
    self.hasNextPage = YES;
    self.currentPage = @0;
    self.totalCount = @0;
    [self loadData];
}

- (BOOL)isReload {
    _isReload = (self.totalCount.integerValue == 0);
    return _isReload;
}

//- (BOOL)hasNextPage {
//    _hasNextPage = self.totalCount.integerValue <= 0
//    || self.pageSize.integerValue * self.currentPage.integerValue < self.totalCount.integerValue;
//    return _hasNextPage;
//}

//Override
- (BOOL)isLoading {
    return isLoading;
}

//Override
- (void)showLoading {
    isLoading = YES;
    
    //数据为空的时候显示Loading框
    if ([self.targetTableView respondsToSelector:@selector(numberOfSections)]) {
        NSInteger sectionCount = [self.targetTableView numberOfSections];
        if(sectionCount == 0){
            [super showLoading];
        }
        for(NSInteger i = 0; i < sectionCount; i++){
            if([self.targetTableView numberOfRowsInSection:i] <= 0){
               [super showLoading];
            }
        }
    }else{
        if([self.targetTableView numberOfRowsInSection:0] <= 0){
           [super showLoading];
        }
    }
}

//Override
- (void)hideLoading {
    isLoading = NO;
    [super hideLoading];
    
    __weak UITableView *tableView = [self targetTableView];
    [tableView.mj_header endRefreshing];
    [tableView.mj_footer endRefreshing];
}


-(void)hideLoadingForWorkDetail{
    isLoading = NO;
    __weak UITableView *tableView = [self targetTableView];
    [tableView.mj_header endRefreshing];
    [tableView.mj_footer endRefreshing];
}

- (void)appendDataList:(NSArray<Optional> *)result setPage:(NSInteger)page{
    [self appendDataList:result setPage:page setType:0 setTips:@""];
}


-(void)appendDataList:(NSArray<Optional> *)result setPage:(NSInteger)page setType:(NSInteger)type setTips:(NSString *)tips{
    [self appendDataList:result setPage:page setType:type isShowEmptyView:YES setTips:tips];
}

-(void)appendDataList:(NSArray<Optional> *)result setPage:(NSInteger)page setType:(NSInteger)type isShowEmptyView:(BOOL)isShow setTips:(NSString *)tips{
    __weak UITableView *tableView = [self targetTableView];
    //如果加载的数据是第一页,删除原来的数据
    if(page == 1){
        self.isReload = NO;
        [self.dataList removeAllObjects];
    }
    
    self.currentPage = @(page);

    if (result!= nil && result.count > 0) {
        [self.dataList addObjectsFromArray:result];
    }
    
    if ([self hasNextPage]) {
        tableView.mj_footer.hidden = NO;
        [tableView.mj_footer resetNoMoreData];
    }else{
        tableView.mj_footer.hidden = YES;
        [tableView.mj_footer endRefreshingWithNoMoreData];
    }
    [tableView reloadData];
    
    if (self.dataList.count <= 0 && isShow) {
        [self showEmptyView:type setTips:tips];
    }else{
        [self hideEmptyView];
    }
}

- (void)showError:(NSError *)error setType:(NSInteger)type{
    if(type > 0){
//        [self.dataList removeAllObjects];
//        UITableView *tbv = [self targetTableView];
//        [self removeFooterView];
//        [tbv reloadData];
        if(self.dataList.count <= 0){
            if ([error.domain isEqualToString:NSURLErrorDomain]) {
                //网络链接失败,请重试
                [self showEmptyView:KWMNoNework setTips:@""];
            }else{
                [self showEmptyView:KWMLoadFailure setTips:@""];
            }
        }else{
            [super showError:error];
        }
        
    }else{
        [super showError:error];
    }
}

-(void)showEmptyView:(NSInteger)type setTips:(NSString *)tips{
    [self hideEmptyView];
    UITableView *tbv = [self targetTableView];
    tbv.backgroundColor = [UIColor clearColor];
    NSInteger headerHeight = tbv.tableHeaderView.frame.size.height;
    UIView *emptyView = [[UIView alloc] initWithFrame:CGRectMake(0, headerHeight, UI_SCREEN_WIDTH, CGRectGetHeight(tbv.frame) - headerHeight)];
    emptyView.backgroundColor = [UIColor clearColor];
    emptyView.layer.borderColor = [[UIColor blackColor]CGColor];
    UIView *childView;
    if(type == KWMTextTips){//文字提示
        childView = [self getTxtTipsView:emptyView];
    }else{
        childView = [self getHasImageView:emptyView setType:type setTips:tips];
    }
    [emptyView addSubview:childView];

    if(type == KWMTextTips){
        [self.view insertSubview:emptyView belowSubview:tbv];
    }else{
        [self.view insertSubview:emptyView aboveSubview:tbv];
    }
    
    weakEmptyView = emptyView;
    
    
}

-(UIView *)getTxtTipsView:(UIView *)emptyView{
    NSString *msg = NSLocalizedString(@"InfoEmptyData", @"InfoEmptyData");
    NSInteger labelY =  (emptyView.frame.size.height)/2;
    
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, labelY,UI_SCREEN_WIDTH, 35)];
    label.textAlignment = NSTextAlignmentCenter;
    label.textColor = [UIColor darkGrayColor];
    label.font = [UIFont systemFontOfSize:16.0f];
    label.text = msg;
    return label;
    
    
}

//有图片的提示view
-(UIView *)getHasImageView:(UIView *)emptyView setType:(NSInteger)type setTips:(NSString *)tips{
    NSInteger childViewY =  CGRectGetHeight(emptyView.frame)/2-130;//130是空view高度的一半
    NSInteger childViewX = CGRectGetWidth(emptyView.frame)/2-100;//100是空view宽度的一半
    NSString *firstMsg = @"";
    NSString *secondMsg = @"";
    
    UIView *childView = [[UIView alloc] initWithFrame:CGRectMake(childViewX, childViewY, 200, 250)];
    childView.backgroundColor = [UIColor clearColor];
    UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(30, 0, 140, 100)];
    imageView.clipsToBounds = YES;
    NSString *imageName = @"";
    if(type == KWMNoDataTips){//没有数据的
        firstMsg = @"暂时没有找到数据";
        if(tips != nil){
            firstMsg = [NSString stringWithFormat:@"暂时没有找到%@",tips];
        }
        imageName = @"img_nothing";
    }else if(type == KWMNoLike){
        firstMsg = @"你暂时还木有收到赞赏";
        imageName = @"img_empty_like";
    }else if(type == KWMNoNework){//没有网络的
        firstMsg = @"网络已断开噢";
        secondMsg = @"请检查手机网络连接";
        imageName = @"img_nonet";
    }else if(type == KWMLoadFailure){//加载失败的
        firstMsg = @"网络加载失败噢";
        imageName = @"img_slownet";
    }else if(type == KWMNoComment){//没有评论的
        firstMsg = @"暂时还木有收到评论噢";
        imageName = @"img_nocomment";
    }else if(type == KWMNoFans){//没有关注的
        firstMsg = @"你暂时还没有朋友关注哦";
        imageName = @"img_unlogin";
    }else if(type == KWMNoCollect){
        firstMsg = @"你作品暂时还木有被收藏";
        imageName = @"img_nocollect";
    }
    [imageView setImage:[UIImage imageNamed:imageName]];
    imageView.contentMode = UIViewContentModeScaleAspectFit;
    [childView addSubview:imageView];
    UILabel *lbFirst = [[UILabel alloc] initWithFrame:CGRectMake(0, 110,200, 20)];
    lbFirst.textAlignment = NSTextAlignmentCenter;
    lbFirst.textColor = [UIColor sam_colorWithHex:@"666666"];
    lbFirst.font = [UIFont systemFontOfSize:13.0f];
    lbFirst.text = firstMsg;
    [childView addSubview:lbFirst];
    UILabel *lbSecond = [[UILabel alloc] initWithFrame:CGRectMake(0, 140,200, 21)];
    lbSecond.textAlignment = NSTextAlignmentCenter;
    lbSecond.textColor = [UIColor sam_colorWithHex:@"666666"];
    lbSecond.font = [UIFont systemFontOfSize:13.0f];
    lbSecond.text = secondMsg;
    [childView addSubview:lbSecond];
    NSString *btnMsg = @"点击刷新";
    UIButton *btn = [[UIButton alloc] initWithFrame:CGRectMake(10, 170, 180, 40)];
    btn.backgroundColor = [UIColor clearColor];//FDA03D
    btn.clipsToBounds = YES;
    btn.userInteractionEnabled = YES;
    btn.layer.borderWidth = 1;
    btn.layer.borderColor = [[UIColor sam_colorWithHex:@"FDA03D"] CGColor];
    btn.layer.cornerRadius = 20;
    [btn setTintColor:[UIColor whiteColor]];
    [btn setTitleColor:[UIColor sam_colorWithHex:@"FDA03D"] forState:UIControlStateNormal];
    btn.titleLabel.font = [UIFont systemFontOfSize: 14.0];
    [btn setTitle:btnMsg forState:UIControlStateNormal];
    [btn addTarget:self action:@selector(onClickEmptyViewBtn) forControlEvents:UIControlEventTouchUpInside];
    [childView addSubview:btn];
    return childView;
}

//点击按钮的
-(void)onClickEmptyViewBtn{
    [self reLoadData];
}

-(void)hideEmptyView{
    if(weakEmptyView != nil){
        weakEmptyView.hidden = YES;
        [weakEmptyView removeFromSuperview];
        weakEmptyView = nil;
    }
}


#pragma mark - EGORefreshTableDelegate

- (void)egoRefreshTableDidTriggerRefresh:(EGORefreshPos)aRefreshPos {
    switch (aRefreshPos){
        case EGORefreshHeader:{
            [self reLoadData];
            break;
        }
        case EGORefreshFooter:{
            [self loadData];
            break;
        }
    }
}

- (BOOL)egoRefreshTableDataSourceIsLoading:(UIView *)view {
    return [self isLoading];
}

- (NSDate *)egoRefreshTableDataSourceLastUpdated:(UIView *)view {
    return [NSDate date];
}

#pragma mark UITableViewDataSource

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    NSAssert(NO, @"子类必须重写该方法");
    return 0;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    NSAssert(NO, @"子类必须重写该方法");
    return nil;
}

@end