//
//  KKListenSubController.m
//  Open
//
//  Created by 雷俊博 on 2020/6/4.
//  Copyright © 2020 黄江涛 . All rights reserved.
//

#import "KKListenSubController.h"
#import "KKListenSubCell.h"
#import "UIImageView+WebCache.h"

@interface KKListenSubController ()<UITableViewDelegate,UITableViewDataSource>
{
    NSInteger currentPage;
}

@property (nonatomic, strong)UITableView*tableView;

@property (nonatomic, strong)NSMutableArray*dataArray;

@end

@implementation KKListenSubController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.dataArray = [NSMutableArray array];
    
    currentPage = 1;
    
    [self.view addSubview:self.tableView];
    
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.bottom.right.offset(0);
    }];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    [self loadData];
    
    [self.tableView setContentOffset:CGPointZero];
}



- (void)loadData
{
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    [params setObject:@(self.model.categoryId) forKey:@"category_id"];
    [params setObject:@1 forKey:@"calc_dimension"];
    [params setObject:@20 forKey:@"count"];
    [params setObject:@(currentPage) forKey:@"page"];
    __weak typeof(self) sself = self;
    [[XMReqMgr sharedInstance] requestXMData:XMReqType_AlbumsList params:params withCompletionHander:^(id result, XMErrorModel *error) {
        
        [self.tableView.mj_header endRefreshing];
        [self.tableView.mj_footer endRefreshing];
        
        if (currentPage == 1) {
             [self.dataArray removeAllObjects];
        }
        
        if (!error){
            
            NSArray*array  =  [sself showReceivedData:result className:@"XMAlbum" valuePath:@"albums" titleNeedShow:@"albumTitle"];
            if (array.count > 0) {
                for (XMAlbum* album in array) {
                               [self.dataArray addObject:album];
                           }
                           
                           if (array.count %20 != 0) {
                               [self.tableView.mj_footer resetNoMoreData];
                           }
                           
                           
                       
                          
            }else{
                [self.tableView.mj_footer resetNoMoreData];
            }
            
            self->currentPage++;
             [self.tableView reloadData];
           
        }else {
           NSLog(@"Error: error_no:%ld, error_code:%@, error_desc:%@",(long)error.error_no, error.error_code, error.error_desc);
        }
    }];
}

- (UIView *)footerView
{
    UIView*view = [[UIView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, 40)];
    view.backgroundColor = [UIColor whiteColor];
    UILabel*lb_title = [[UILabel alloc]init];
    lb_title.text = @"已加载所有动态~";
    lb_title.textColor = [UIColor colorWithHex:0x808080];
    lb_title.font = [UIFont systemFontOfSize:12];
    lb_title.textAlignment = NSTextAlignmentCenter;
    [view addSubview:lb_title];
    [lb_title mas_makeConstraints:^(MASConstraintMaker *make) {
        make.center.equalTo(view);
        make.top.left.offset(15);
        make.bottom.right.offset(-15);
    }];
    return view;
}

- (NSMutableArray *)showReceivedData:(id)result className:(NSString*)className valuePath:(NSString *)path titleNeedShow:(NSString*)title
{
    NSMutableArray *models = [NSMutableArray array];
    Class dataClass = NSClassFromString(className);
    if([result isKindOfClass:[NSArray class]]){
        for (NSDictionary *dic in result) {
            id model = [[dataClass alloc] initWithDictionary:dic];
            [models addObject:model];
        }
    }
    else if([result isKindOfClass:[NSDictionary class]]){
        if(path.length == 0)
        {
            id model = [[dataClass alloc] initWithDictionary:result];
            [models addObject:model];
        }
        else
        {
            NSArray *paths = [path componentsSeparatedByString:@"."];
            
//            NSLog(@"paths have %lu objects inside", (unsigned long)[paths count]);
//            NSLog(@"paths last object is %@", paths.lastObject);
            
            NSDictionary *dic = result;
            for (int i=0;i<paths.count-1;i++)
            {
                NSString *subPath = paths[i];
                dic = dic[subPath];
            }
            for (NSDictionary *dict in dic[paths.lastObject])
            {
                id model = [[dataClass alloc] initWithDictionary:dict];
                [models addObject:model];
                
            }
        }
    }
    
    return models;
}

#pragma mark - UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return self.dataArray.count;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 1;
}

// Row display. Implementers should *always* try to reuse cells by setting each cell's reuseIdentifier and querying for available reusable cells with dequeueReusableCellWithIdentifier:
// Cell gets various attributes set automatically based on table (separators) and data source (accessory views, editing controls)

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    KKListenSubCell* cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    
    XMAlbum*model = self.dataArray[indexPath.section];
    
    [cell.img sd_setImageWithURL:[NSURL URLWithString:model.coverUrlLarge
                                  ] placeholderImage:[UIImage imageNamed:@""]];
    cell.lb_title.text = model.albumTitle;
    
    cell.lb_subTitle.text = model.albumIntro;
    cell.lb_count.text = [self getStrWithCount:model.playCount];
    
    return cell;
}

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

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 10;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 0.1;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    XMAlbum*model = self.dataArray[indexPath.section];
    if (self.delegate && [self.delegate respondsToSelector:@selector(didSelectedWithVC:model:)]) {
        [self.delegate didSelectedWithVC:self model:model];
    }
}



#pragma mark - private methods
- (NSString *)getStrWithCount:(NSInteger)count
{
    if (count < 10000) {
        return [NSString stringWithFormat:@"%ld",count];
    }else if (count < 100000000&& count>= 10000 ){
        return [NSString stringWithFormat:@"%ld万",count/10000];
    }else{
         return [NSString stringWithFormat:@"%ld亿",count/100000000];
    }
}


#pragma mark - getters and setters
- (UITableView *)tableView
{
    if (!_tableView) {
        _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, self.view.bounds.size.height) style:UITableViewStyleGrouped];
        _tableView.showsVerticalScrollIndicator = NO;
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.estimatedSectionHeaderHeight = 0;
        _tableView.estimatedSectionFooterHeight = 0;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        [_tableView registerNib:[UINib nibWithNibName:@"KKListenSubCell" bundle:nil] forCellReuseIdentifier:@"cell"];
        
        _tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
            currentPage = 1;
           
            [self loadData];
        }];
        _tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
               [self loadData];
           }];
    }
    return _tableView;
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
