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

#import "KKPlayerListView.h"
#import "KKListenDetailCell.h"
#import "KKMusicPlayListCell.h"
#import "ICMusicPlayManager.h"


@interface KKPlayerListView ()<UITableViewDelegate,UITableViewDataSource,KKMusicPlayListCellDelegate,UIGestureRecognizerDelegate>
{
    NSInteger _playingIndex;
    XMSDKPlayer *_sdkPlayer;
}

@property (nonatomic, strong)UIView* contentView;



@property (nonatomic, assign)NSInteger index;



@property (nonatomic, strong)XMAlbum*model;

@property (nonatomic, assign)NSInteger currentPage;



@property(nonatomic, strong) NSMutableArray *statueArray;

@end

@implementation KKPlayerListView
- (instancetype)initWithData:(NSArray *)dataArray index:(NSInteger)index model:(XMAlbum *)albumModel currentPage:(NSInteger)currentPage
{
    self = [super init];
    if (self) {
         _sdkPlayer = [XMSDKPlayer sharedPlayer];
        self.currentPage = currentPage;
        self.model = albumModel;
        self.dataArray = [NSMutableArray arrayWithArray:dataArray];
        
        self.index = index;
        
        _statueArray = @[].mutableCopy;
        
         [self setStatueWithAllData:self.dataArray CurrentIndex:_index];
        
        
        [self creatUI];
    }
    return self;
}

- (void)creatUI
{
    self.frame = [UIScreen mainScreen].bounds;
    self.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.5];
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapClick:)];
    tap.delegate = self;
    [self addGestureRecognizer:tap];
    
    //------- 弹窗主内容 -------//
    self.contentView = [[UIView alloc] init];
    self.contentView.frame = CGRectMake(0, ScreenHeight - 450 * WIDTHRADIU, ScreenWidth, 450 * WIDTHRADIU);
    [self addSubview:self.contentView];
    
    UIBezierPath *cornerRadiusPath = [UIBezierPath bezierPathWithRoundedRect:self.contentView.bounds byRoundingCorners:UIRectCornerTopRight | UIRectCornerTopLeft cornerRadii:CGSizeMake(15 * WIDTHRADIU, 15 * WIDTHRADIU)];

    CAShapeLayer *cornerRadiusLayer = [ [CAShapeLayer alloc ] init];

    cornerRadiusLayer.frame = self.contentView.bounds;

    cornerRadiusLayer.path = cornerRadiusPath.CGPath;
    self.contentView.layer.mask = cornerRadiusLayer;
    
    UITableView*tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, 410 * WIDTHRADIU) style:UITableViewStyleGrouped];
    tableView.backgroundColor = [UIColor whiteColor];
    tableView.showsVerticalScrollIndicator = NO;
    tableView.delegate = self;
    tableView.dataSource = self;
    tableView.separatorStyle =  UITableViewCellSeparatorStyleNone;
    tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        [self loadData];
    }];
    
   
    //[tableView registerNib:[UINib nibWithNibName:@"KKListenDetailCell" bundle:nil] forCellReuseIdentifier:@"cell"];
    self.tableView = tableView;
    //tableView.tableHeaderView = [MJRefreshHeader ]
    [self.contentView addSubview:tableView];
    
    if (self.dataArray.count > 0 && self.dataArray.count % 100 != 0) {
           self.tableView.mj_footer = nil;
           self.tableView.tableFooterView = [self footerView];
       }
    
    //关闭按钮
    UIButton*closeBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    closeBtn.frame = CGRectMake(0, 410* WIDTHRADIU, ScreenWidth, 40 * WIDTHRADIU);
    [closeBtn setTitle:@"关闭" forState:UIControlStateNormal];
    closeBtn.backgroundColor = [UIColor whiteColor];
    closeBtn.titleLabel.font = [UIFont systemFontOfSize:15 * WIDTHRADIU];
    [closeBtn setTitleColor:[UIColor colorWithHex:0x4d4d4d] forState:UIControlStateNormal];
    [closeBtn addTarget:self action:@selector(closeBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    closeBtn.layer.borderWidth = 0.5;
    closeBtn.layer.borderColor = [UIColor colorWithHex:0xcccccc].CGColor;
    [self.contentView addSubview:closeBtn];
    
    
    
}

#pragma mark - loadData
- (void)loadData
{
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
       [params setObject:@(self.model.albumId) forKey:@"album_id"];
       [params setObject:@100 forKey:@"count"];
    [params setObject:@(self.currentPage) forKey:@"page"];
       
       [[XMReqMgr sharedInstance] requestXMData:XMReqType_AlbumsBrowse params:params
       withCompletionHander:^(id result, XMErrorModel *error) {
           [self.tableView.mj_footer endRefreshing];
           [self.tableView.mj_header endRefreshing];
           if (!error) {
               self.currentPage++;
               NSArray*array = [self showReceivedData:result className:@"XMTrack" valuePath:@"tracks" titleNeedShow:nil];
               if (array.count < 100) {
                   self.tableView.mj_footer = nil;
                   self.tableView.tableFooterView = [self footerView];
               }
               for (XMTrack*track in array) {
                   [self.dataArray addObject:track];
               }
               [self->_sdkPlayer replacePlayList:self.dataArray];
               [self setStatueWithAllData:self.dataArray CurrentIndex:[self getIndex]];
               
               [self.tableView reloadData];
           }else{
               NSLog(@"error:%@",error);
           }
           
       }];
}

- (NSInteger)getIndex
{
    XMTrack*currentTrack = [_sdkPlayer currentTrack];
    NSArray*array = [_sdkPlayer playList];
    NSInteger index = 0;
    for (int i = 0; i < array.count; i++) {
        XMTrack* track = array[i];
        if (track.trackId == currentTrack.trackId) {
            index = i;
            break;
        }
    }
    
    return index;
}

#pragma mark - getters
- (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;
}

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


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    XMTrack*model = self.dataArray[indexPath.row];
    KKMusicPlayListCell*cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    if (!cell) {
        cell = [[KKMusicPlayListCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell"];
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.backgroundColor = [UIColor whiteColor];
    cell.delegate = self;
    
    
   
    //[cell.playBtn addTarget:self action:@selector(playBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    cell.playModel = model;
    
    BOOL isPlaying = [[XMSDKPlayer sharedPlayer] isPlaying];
    cell.playStatue = isPlaying;
    cell.isPlaying = [_statueArray[indexPath.row] isEqualToString:@"1"] ? YES : NO;
    cell.index = indexPath.row;

    return cell;
}

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

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [self dismissUI];
    if (_index == indexPath.row) {
        return;
    }
    
    _index = indexPath.row;
    [self setStatueWithAllData:self.dataArray CurrentIndex:_index];
    [self.tableView reloadData];
    XMTrack*model = self.dataArray[indexPath.row];
    if (self.KKPlayerListViewDidSelectedBlock) {
        self.KKPlayerListViewDidSelectedBlock(model,self.dataArray, _index);
    }
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    XMTrack*model = self.dataArray[indexPath.row];
    
    CGRect labelSize = [model.trackTitle boundingRectWithSize:CGSizeMake(ScreenWidth - 107, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesFontLeading attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:16]} context:nil];
    if (labelSize.size.height > 30) {
        return 97;
    }
    
    return 77;
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate {
    if (scrollView == self.tableView) {
        [self.tableView reloadData];
    }
}



#pragma mark - KKMusicPlayListCellDelegate
- (void)btnClickWithCell:(KKMusicPlayListCell *)cell Btn:(UIButton *)btn model:(nonnull XMTrack *)model
{
    
    [self dismissUI];
    if (_index == cell.index) {
        return;
    }
    
    _index = cell.index;
    [self setStatueWithAllData:self.dataArray CurrentIndex:_index];
    [self.tableView reloadData];
    XMTrack*Kmodel = self.dataArray[_index];
    if (self.KKPlayerListViewDidSelectedBlock) {
        self.KKPlayerListViewDidSelectedBlock(Kmodel,self.dataArray,_index);
    }
}

#pragma mark - UIGestureRecognizerDelegate
- (BOOL)gestureRecognizerShouldBegin:(UIGestureRecognizer*)gestureRecognizer {

    UITapGestureRecognizer *tap = (UITapGestureRecognizer *)gestureRecognizer;

    CGPoint point = [tap locationInView:self];

    BOOL isIn = CGRectContainsPoint(self.contentView.frame,point);
    return !isIn;

}


#pragma mark - data
- (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 - event response
- (void)tapClick:(UITapGestureRecognizer *)ges
{
    NSLog(@"1423143");
    [self dismissUI];
}

- (void)closeBtnClick:(UIButton *)sender
{
    [self dismissUI];
}

#pragma mark - 隐藏和显示
- (void)dismissUI
{
    if (self.KKPlayerListViewHiddenBlock) {
        self.KKPlayerListViewHiddenBlock();
    }
}

- (void)playBtnClick:(UIButton *)sender
{
    
}



- (void)setStatueWithAllData:(NSArray *)allDate CurrentIndex:(NSInteger)currentIndex {
    [_statueArray removeAllObjects];
    for (NSInteger i = 0; i < allDate.count; i++) {
        if (currentIndex == i) {
            [_statueArray addObject:@"1"];
        }else {
            [_statueArray addObject:@"0"];
        }
    }
}

- (void)setCurrentIndex:(NSInteger)currentIndex
{
    _currentIndex = currentIndex;
    _index = currentIndex;
    [self setStatueWithAllData:self.dataArray CurrentIndex:_index];
    
    [self.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:currentIndex inSection:0] atScrollPosition:UITableViewScrollPositionMiddle animated:YES];
}

/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/

@end
