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

#import "KKListenSub2Controller.h"
#import "RecommendViewCell.h"
#import "Recommend2ViewCell.h"
#import "XMSDK.h"
#import "LMHWaterFallLayout.h"

#import "UIImageView+WebCache.h"

@interface KKListenSub2Controller ()<LMHWaterFallLayoutDeleaget,UICollectionViewDataSource,RecommendViewCellDelegate,UIScrollViewDelegate>


@property (nonatomic, strong)UICollectionView* collectionView;

@property (nonatomic, strong)NSArray* dataArray;

@property (nonatomic, strong)UIImageView*topBackBg;


@end

@implementation KKListenSub2Controller

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor colorWithHex:0xf4f4f4];
    [self.view addSubview:self.topBackBg];
    [self.view addSubview:self.collectionView];
    
    [self.topBackBg mas_makeConstraints:^(MASConstraintMaker *make) {
         make.top.left.right.offset(0);
        make.height.offset(13 * WIDTHRADIU);
    }];
    [self.collectionView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.bottom.right.offset(0);
        make.top.equalTo(self.topBackBg.mas_bottom).offset(0);
    }];
    
    [self loadData];
}

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

#pragma mark - loaddata
- (NSDictionary *)getXMLYTuiJianRequestPara
{
    NSDictionary* params = @{
        @"is_paid":@0,
        @"count":@100
    };
    return params;
}
- (void)loadData
{
    NSString*url = [NSString stringWithFormat:@"%@%@",[NetworkConfig ipBackUrlConfig],XMLYTuiJianRequest];
    WeakSelf
    [NetworkRequest Get4:url Params:[self getXMLYTuiJianRequestPara]  Success:^(id _Nonnull objc) {
         __strong typeof(self) strongSelf = weakSelf;
        strongSelf.dataArray = [strongSelf showReceivedData:objc className:@"XMAlbum" valuePath:@"albums" titleNeedShow:@"albumTitle"];
        [strongSelf.collectionView reloadData];
        
        
    } Failure:^(NSError* error) {
        
    }];
    
}

- (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 - UICollectionViewDataSource
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return 2;
}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    if (section == 0) {
        return 1;
    }
    return self.dataArray.count;
}

// The cell that is returned must be retrieved from a call to -dequeueReusableCellWithReuseIdentifier:forIndexPath:
- (__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        RecommendViewCell* cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cell" forIndexPath:indexPath];
        cell.delegate = self;
        cell.backgroundColor = [UIColor whiteColor];
        return cell;
    }
    Recommend2ViewCell* cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cell2" forIndexPath:indexPath];
    cell.backgroundColor = [UIColor whiteColor];
    XMAlbum*model = self.dataArray[indexPath.row];
    
    [cell.img sd_setImageWithURL:[NSURL URLWithString:model.coverUrlLarge
                                  ] placeholderImage:[UIImage imageNamed:@""]];
    cell.lb_title.text = model.albumTitle;
    
    cell.lb_count.text = [self getStrWithCount:model.playCount];
    return cell;
}

/**
 cell的大小
 */
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0) {
        return CGSizeMake(ScreenWidth - 30, 360);
    }
    XMAlbum*model = self.dataArray[indexPath.row];
    
    CGFloat height = [self getLabelHeightWithText:model.albumTitle width:((ScreenWidth - 40)/2 - 10) font:[UIFont boldSystemFontOfSize:15]];
    if (height > 19) {
         return CGSizeMake((ScreenWidth - 40)/2, (ScreenWidth - 40)/2 + 75);
    }else{
        return CGSizeMake((ScreenWidth - 40)/2, (ScreenWidth - 40)/2 + 57);
    }
    
}

/**
 每个分区的内边距（上左下右）
 */
- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section{
    if (section == 0) {
        return UIEdgeInsetsMake(15, 15, 20, 15);
    }
    return UIEdgeInsetsMake(0, 15, 0, 15);
}


/**
 分区内cell之间的最小行间距
 */
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section{
    if (section == 0) {
        return 0.0;
    }
    return 10.0;
}
/**
 分区内cell之间的最小列间距
 */
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section{
    if (section == 0) {
        return 0.0;
    }
    return 10.0;
}
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(nonnull NSIndexPath *)indexPath
{
    if (indexPath.section == 1) {
         XMAlbum*model = self.dataArray[indexPath.row];
        if (self.delegate && [self.delegate respondsToSelector:@selector(ClickItemWithModel:)]) {
            [self.delegate ClickItemWithModel:model];
        }
    }
}

#pragma mark - RecommendViewCellDelegate
- (void)didSelectCell:(RecommendViewCell *)cell model:(XMAlbum *)album
{
    if (self.delegate && [self.delegate respondsToSelector:@selector(ClickItemWithModel:)]) {
            [self.delegate ClickItemWithModel:album];
        }
}
#pragma mark  - <LMHWaterFallLayoutDeleaget>
- (CGFloat)waterFallLayout:(LMHWaterFallLayout *)waterFallLayout heightForItemAtIndexPath:(NSUInteger)indexPath itemWidth:(CGFloat)itemWidth{
    
    
    
    XMAlbum*model = self.dataArray[indexPath];
    
    CGFloat height = [self getLabelHeightWithText:model.albumTitle width:((ScreenWidth - 40)/2 - 10) font:[UIFont boldSystemFontOfSize:15]];
    if (height > 19) {
         return (ScreenWidth - 40)/2 + 75;
    }else{
        return (ScreenWidth - 40)/2 + 57;
    }
}

- (CGFloat)minYInwaterFallLayout:(LMHWaterFallLayout *)waterFallLayout
{
    return 380;
}

- (CGFloat)rowMarginInWaterFallLayout:(LMHWaterFallLayout *)waterFallLayout{
    
    return 10;
    
}

- (CGFloat)columnMarginInWaterFallLayout:(LMHWaterFallLayout *)waterFallLayout
{
    return 10;
}

- (NSUInteger)columnCountInWaterFallLayout:(LMHWaterFallLayout *)waterFallLayout{
    
    return 2;
    
}


#pragma mark - UIScrollViewDelegate
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    NSLog(@"contentOffset.y:%.2f",scrollView.contentOffset.y);
    
    BOOL isTop = NO;
    if (scrollView.contentOffset.y >=10) {
        isTop = YES;
    }
    
    self.topBackBg.hidden = isTop;
    
    if (isTop) {
        [self.collectionView mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.top.left.bottom.right.offset(0);
        }];
    }else{
        [self.collectionView mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.left.bottom.right.offset(0);
            make.top.equalTo(self.topBackBg.mas_bottom).offset(0);
        }];
    }
    
    if (self.delegate && [self.delegate respondsToSelector:@selector(scrollToTop:)]) {
        [self.delegate scrollToTop:isTop];
    }
}


#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];
    }
}

//根据文本计算控件宽度
- (CGFloat)getLabelHeightWithText:(NSString *)text width:(CGFloat)width font:(UIFont *)font
{
    CGRect rect = [text boundingRectWithSize:CGSizeMake(width, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:font} context:nil];
    return rect.size.height;
}

#pragma mark - getters and setters
- (UICollectionView *)collectionView
{
    if (!_collectionView) {
//        UICollectionViewFlowLayout *fl = [[UICollectionViewFlowLayout alloc]init];
//        fl.scrollDirection = UICollectionViewScrollDirectionVertical;
//        fl.minimumLineSpacing = 10;
//        fl.minimumInteritemSpacing = 10;
        // 创建布局
        LMHWaterFallLayout * waterFallLayout = [[LMHWaterFallLayout alloc]init];
        waterFallLayout.delegate = self;
        
        _collectionView = [[UICollectionView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, ScreenHeight - cl_kNavigationBarHeight) collectionViewLayout:waterFallLayout];
        _collectionView.delegate = self;
        _collectionView.dataSource = self;
        _collectionView.showsVerticalScrollIndicator = NO;
        _collectionView.backgroundColor = [UIColor clearColor];
        [_collectionView registerNib:[UINib nibWithNibName:@"RecommendViewCell" bundle:nil] forCellWithReuseIdentifier:@"cell"];
        [_collectionView registerNib:[UINib nibWithNibName:@"Recommend2ViewCell" bundle:nil] forCellWithReuseIdentifier:@"cell2"];
    }
    return _collectionView;
}

- (UIImageView *)topBackBg
{
    if (!_topBackBg) {
        _topBackBg = [[UIImageView alloc]init];
        _topBackBg.image = [UIImage imageNamed:@"jingtie_topbg"];
    }
    return _topBackBg;
}

/*
#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
