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

#import "KKListenDetailController.h"
#import "UIImageView+WebCache.h"
#import "KKListenDetailCell.h"
#import "KKXMDetailModel.h"
#import "KKPlayerViewController.h"
#import "ICMusicPlayManager.h"
#import "ProgressView.h"
#import "KKMusicPlayListCell.h"
#import <MediaPlayer/MediaPlayer.h>

@interface KKListenDetailController ()<UITableViewDelegate,UITableViewDataSource,KKMusicPlayListCellDelegate>
{
    XMSDKPlayer *_sdkPlayer;
    
    
    NSInteger _selectIndex;
    
    UIButton*lastBtn;
    UIButton*currentBtn;
    NSInteger currentPage;
}

@property (nonatomic, strong)UIImageView* topBackImg;

@property (nonatomic, strong)UIImageView* avtalImg;

@property (nonatomic, strong)UIView* cardView;

@property (nonatomic, strong)NSMutableArray*dataArray;

@property(nonatomic, strong) NSMutableArray *statueArray;

@property (nonatomic, strong)UITableView* tableView;

@property (nonatomic, strong)UIImageView* iconImg;

@property (nonatomic, strong)ProgressView* progressView;

@property (nonatomic, strong)UIView* shadowView;

@property (nonatomic, assign)XMSDKPlayerState playingState;



@end

@implementation KKListenDetailController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.automaticallyAdjustsScrollViewInsets = NO;
    self.view.backgroundColor = [UIColor whiteColor];
    self.dataArray = [NSMutableArray array];
    _statueArray = @[].mutableCopy;
    currentPage = 1;
    
    
    [self creatUI];
    [self navConfig];
    
    
   
    [self loadData];
     _sdkPlayer = [XMSDKPlayer sharedPlayer];
     [_sdkPlayer setPlayMode:XMSDKPlayModeTrack];
     [_sdkPlayer setTrackPlayMode:XMTrackPlayerModeList];
     [_sdkPlayer setAutoNexTrack:YES];
    
    
    
    
    
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
     [self.navigationController setNavigationBarHidden:YES];
    
    [self getPlayingStateAndRefreshUI];
    
    
    
    ICMusicPlayManager*manager = [ICMusicPlayManager sharedManager];
    manager.KKPlayerPlayTimeChanged = ^(CGFloat percent, NSUInteger currentSecond) {
        NSLog(@"kk:percent:%.2lf,current:%ld",percent,currentSecond);
        self.progressView.percent = percent;
    };
    manager.KKPlayerDidError = ^(NSString * _Nonnull type, NSDictionary * _Nonnull data) {
        [SVProgressHUD dismiss];
    };
    
    manager.KKPlayerDidStart = ^{
        [SVProgressHUD dismiss];
       
        XMTrack*track1 = [self->_sdkPlayer currentTrack];
        [self addArcImg:track1];
        [self getPlayingStateAndRefreshUI];
        
        [self setupLockScreenMediaInfo:track1];
        [self SaveTrackDataRequest:track1];
    };
    manager.KKPlayerDidPaused = ^{
        [self getPlayingStateAndRefreshUI];
        [self animationPauseWithView:self.iconImg];
    };
    
    manager.KKPlayerDidPlaying = ^{
         [self getPlayingStateAndRefreshUI];
         [self animationResumeWithView:self.iconImg];
    };
    
   
    
    
}

#pragma mark - loadData
- (void)loadData
{
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
       [params setObject:@(self.model.albumId) forKey:@"album_id"];
       [params setObject:@100 forKey:@"count"];
       [params setObject:@(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);
           }
           
       }];
}

- (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;
}


//存储播放记录
- (NSDictionary *)SaveTrackDataRequestPara:(XMTrack *)track
{
    
    NSString *adId = [[[ASIdentifierManager sharedManager] advertisingIdentifier] UUIDString];
    NSString*phone = nil;
    if (![[NSUserDefaults standardUserDefaults] boolForKey:@"firstlog"]) {
        phone = adId;
    }else{
        phone = [EnercryTool encryptUseDES:[getPeopleID PeopleIphoneNmber] key:DESKEY];
    }
    NSDictionary*para = @{
        @"albumid":@(track.subordinatedAlbum.albumId),
        @"trackid":@(track.trackId),
        @"albumtitle":[NSString validBlankStr:track.subordinatedAlbum.albumTitle],
        @"pageindex":[NSString stringWithFormat:@"%ld",track.orderNum + 1],
        @"allpageindex":@(self.model.includeTrackCount),
        @"imageurl":[NSString validBlankStr:track.subordinatedAlbum.coverUrlLarge],
        @"phone":phone,
        @"listentitle":track.trackTitle,
        @"listenindex":@(track.orderNum)
    };
    return para;
}

- (void)SaveTrackDataRequest:(XMTrack *)track
{
    NSString* url = [NSString stringWithFormat:@"%@%@",[NetworkConfig ipXMLYHistoryConfig],XMLYSaveHistoryRequest];
    
    [NetworkRequest Post10:url Params:[self SaveTrackDataRequestPara:track] Success:^(id _Nonnull objc) {
        NSLog(@"objc:%@",objc);
    } Failure:^(NSError* error) {
        NSLog(@"error:%@",error);
    }];
}


- (void)navConfig
{
    [self.navigationController setNavigationBarHidden:YES];
    UIButton * backBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    backBtn.frame = CGRectMake( 10 * WIDTHRADIU, cl_kStatusBarHeight + 9.5, 20, 25);
    backBtn.titleLabel.textAlignment =NSTextAlignmentLeft;
    //    [button_2 setTitle:@"asdasd按时打发第三方" forState:UIControlStateNormal];
    [backBtn setImage:[UIImage imageNamed:@"返回"] forState:UIControlStateNormal];
    //    [button_2 setBackgroundColor:[UIColor redColor]];
    //    [button_2 setTitleColor:[UIColor colorWithRed:12.0 green:12.0 blue:12.0 alpha:1] forState:UIControlStateNormal];
    [backBtn addTarget:self action:@selector(backClick) forControlEvents:UIControlEventTouchUpInside];
    
    [self.topBackImg addSubview:backBtn];
    
    
    
    self.avtalImg = [[UIImageView alloc]init];
    self.avtalImg.frame = CGRectMake(15 * WIDTHRADIU, cl_kNavigationBarHeight + 10 * WIDTHRADIU, 0.35*ScreenWidth,0.35*ScreenWidth);
    self.avtalImg.layer.cornerRadius = 8 * WIDTHRADIU;
    self.avtalImg.layer.masksToBounds = YES;
    [self.avtalImg sd_setImageWithURL:[NSURL URLWithString:self.model.coverUrlLarge]];
    self.avtalImg.contentMode = UIViewContentModeScaleAspectFill;
    [self.topBackImg addSubview:self.avtalImg];
    
    
    //title
    UILabel* lb_title = [[UILabel alloc]init];
    lb_title.textColor = [UIColor whiteColor];
    lb_title.font = [UIFont boldSystemFontOfSize:20 * WIDTHRADIU];
    [self.topBackImg addSubview:lb_title];
    
    lb_title.text = self.model.albumTitle;
    
    [lb_title mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.avtalImg.mas_top).offset(10 * WIDTHRADIU);
        make.left.equalTo(self.avtalImg.mas_right).offset(20 * WIDTHRADIU);
        make.right.offset( - 10 * WIDTHRADIU);
    }];
    
    //副标题
    UILabel* lb_subtitle = [[UILabel alloc]init];
    lb_subtitle.textColor = [UIColor whiteColor];
    lb_subtitle.font = [UIFont boldSystemFontOfSize:12 * WIDTHRADIU];
    lb_subtitle.numberOfLines = 2;
    [self.topBackImg addSubview:lb_subtitle];
    
    lb_subtitle.text = self.model.albumIntro;
    
    [lb_subtitle mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(lb_title.mas_bottom).offset(10 * WIDTHRADIU);
        make.left.equalTo(self.avtalImg.mas_right).offset(20 * WIDTHRADIU);
        make.right.offset( - 10 * WIDTHRADIU);
    }];
    
    //耳机
    UIImageView* erImg = [[UIImageView alloc]init];
    erImg.image = [UIImage imageNamed:@"playHeadset"];
    [self.topBackImg addSubview:erImg];
    
    [erImg mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(lb_title);
        make.top.equalTo(lb_subtitle.mas_bottom).offset(10 * WIDTHRADIU);
        make.width.height.offset(12 * WIDTHRADIU);
    }];
    
    //播放数
    UILabel* lb_count = [[UILabel alloc]init];
    lb_count.textColor = [UIColor whiteColor];
    lb_count.font = [UIFont boldSystemFontOfSize:12 * WIDTHRADIU];
    lb_count.numberOfLines = 2;
    [self.topBackImg addSubview:lb_count];
    
    lb_count.text = [self getStrWithCount:self.model.playCount];
    
    [lb_count mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(erImg);
        make.left.equalTo(erImg.mas_right).offset(3 * WIDTHRADIU);
        make.right.offset( - 10 * WIDTHRADIU);
    }];
    
    //内容来源
    UILabel* lb_from = [[UILabel alloc]init];
    lb_from.textColor = [UIColor whiteColor];
    lb_from.font = [UIFont boldSystemFontOfSize:12 * WIDTHRADIU];
    lb_from.numberOfLines = 2;
    [self.topBackImg addSubview:lb_from];
    
    lb_from.text = @"内容来源：喜马拉雅APP";
    
    [lb_from mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(self.avtalImg.mas_bottom).offset(-10 * WIDTHRADIU);
        make.left.equalTo(erImg);
        make.right.offset( - 10 * WIDTHRADIU);
    }];
    
    
    
}

- (void)creatUI
{
    self.topBackImg = [[UIImageView alloc]init];
    self.topBackImg.frame = CGRectMake(0, 0, ScreenWidth, 0.67*ScreenWidth);
    self.topBackImg.contentMode = UIViewContentModeScaleAspectFill;
    self.topBackImg.userInteractionEnabled = YES;
    self.topBackImg.layer.masksToBounds = YES;
    [self.view addSubview:self.topBackImg];
    
    UIToolbar*bar = [[UIToolbar alloc]initWithFrame:self.topBackImg.bounds];
    bar.barStyle = UIBarStyleBlack;
    bar.alpha = 1.0;
    [self.topBackImg addSubview:bar];
    
    [self.topBackImg sd_setImageWithURL:[NSURL URLWithString:self.model.coverUrlLarge]];
    
    
    self.cardView = [[UIView alloc]initWithFrame:CGRectMake(0, 0.67*ScreenWidth - 15 * WIDTHRADIU, ScreenWidth, ScreenHeight - 0.67*ScreenWidth + 15 * WIDTHRADIU)];
    self.cardView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:self.cardView];
    UIBezierPath *cornerRadiusPath = [UIBezierPath bezierPathWithRoundedRect:self.cardView.bounds byRoundingCorners:UIRectCornerTopRight | UIRectCornerTopLeft cornerRadii:CGSizeMake(15 * WIDTHRADIU, 15 * WIDTHRADIU)];

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

    cornerRadiusLayer.frame = self.cardView.bounds;

    cornerRadiusLayer.path = cornerRadiusPath.CGPath;
    self.cardView.layer.mask = cornerRadiusLayer;
    
    //奖励
    UILabel* lb_message = [[UILabel alloc]init];
    lb_message.textColor = RGBCOLOR(215, 43, 25);
    lb_message.font = [UIFont boldSystemFontOfSize:15 * WIDTHRADIU];
    lb_message.text = @"回顾经典";
    [self.cardView addSubview:lb_message];
    [lb_message mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.offset(20 * WIDTHRADIU);
        make.top.offset(15 * WIDTHRADIU);
    }];
    
    UIView* line = [[UIView alloc]init];
    line.backgroundColor = [UIColor colorWithHex:0xf4f4f4];
    [self.cardView addSubview:line];
    
    [line mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(lb_message.mas_bottom).offset(15 * WIDTHRADIU);
        make.left.right.offset(0);
        make.height.offset(0.5);
    }];
    
    UIImageView* playImg = [[UIImageView alloc]init];
    playImg.image = [UIImage imageNamed:@"playall"];
    [self.cardView addSubview:playImg];
    
    [playImg mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(lb_message);
        make.top.equalTo(line.mas_bottom).offset(10 * WIDTHRADIU);
        make.width.height.offset(21 * WIDTHRADIU);
    }];
    
    //播放全部
    UILabel* lb_playall = [[UILabel alloc]init];
    lb_playall.textColor = RGBCOLOR(25, 26, 26);
    lb_playall.font = [UIFont boldSystemFontOfSize:17 * WIDTHRADIU];
    lb_playall.text = @"播放全部";
    [self.cardView addSubview:lb_playall];
    [lb_playall mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(playImg.mas_right).offset(10 * WIDTHRADIU);
        make.centerY.equalTo(playImg);
    }];
    
    UILabel*lb_num = [[UILabel alloc]init];
    lb_num.textColor = RGBCOLOR(97, 98, 99);
    lb_num.font = [UIFont systemFontOfSize:15 * WIDTHRADIU];
    
    lb_num.text = [NSString stringWithFormat:@"共%ld集",self.model.includeTrackCount];
    [self.cardView addSubview:lb_num];
    [lb_num mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.offset(-15 * WIDTHRADIU);
        make.centerY.equalTo(playImg);
    }];
    
    //tableView;
    UITableView*tableView = [[UITableView alloc]initWithFrame:CGRectZero style:UITableViewStyleGrouped];
    tableView.backgroundColor = [UIColor whiteColor];
    tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    tableView.showsVerticalScrollIndicator = NO;
    tableView.delegate = self;
    tableView.dataSource = self;
    tableView.estimatedSectionHeaderHeight = 0;
    tableView.rowHeight = UITableViewAutomaticDimension;
    tableView.estimatedRowHeight = 77.0f;
    tableView.estimatedSectionFooterHeight = 0;
    
    self.tableView = tableView;
    

    [self.cardView addSubview:tableView];
    [tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(playImg.mas_bottom).offset(10);
        make.left.right.offset(0);
        make.bottom.offset(0);
    }];
    
    if (@available(iOS 11.0, *) ) {
        self.tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
        self.tableView.contentInset = UIEdgeInsetsMake(0, 0, 49, 0);
        self.tableView.scrollIndicatorInsets = self.tableView.contentInset;
    }else{
         self.automaticallyAdjustsScrollViewInsets = NO;
    }
    
    self.tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        [self loadData];
    }];
//    tableView.estimatedSectionHeaderHeight = 0.0;
//    tableView.rowHeight = UITableViewAutomaticDimension;
//    tableView.estimatedSectionFooterHeight = 0.0;
    //[tableView registerNib:[UINib nibWithNibName:@"KKListenDetailCell" bundle:nil] forCellReuseIdentifier:@"cell"];
    
    
    
   

    
    
    
}




#pragma mark - UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}
- (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.playModel = model;
    
    cell.playingState = self.playingState;
    
    
    
    cell.isPlaying = ([self getIndex] == indexPath.row && self.isPlaying);
    
    
    
     cell.index = indexPath.row;
    return cell;
}



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

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    ICMusicPlayManager* manager = [ICMusicPlayManager sharedManager];
    manager.albumModel = self.model;
    
    XMTrack*model = self.dataArray[indexPath.row];
    
    KKPlayerViewController* vc = [KKPlayerViewController new];
    
    vc.model = model;
    
    vc.dataArray = self.dataArray;
    
    if (indexPath.row == 0) {
        vc.hasLastMusic = NO;
        if (self.dataArray.count > 1) {
           vc.hasNextMusic = YES;
        }else{
            vc.hasNextMusic = NO;
        }
        
    }else if (indexPath.row == (self.dataArray.count - 1)){
        vc.hasNextMusic = NO;
        if (self.dataArray.count > 1) {
           vc.hasLastMusic = YES;
        }else{
            vc.hasLastMusic = NO;
        }
    }else{
        vc.hasLastMusic = YES;
        vc.hasNextMusic = YES;
    }
    vc.currentPage = currentPage;
    
    
    
    [self SaveTrackDataRequest:model];
    
    [self.navigationController pushViewController:vc animated:YES];
}

#pragma mark - KKMusicPlayListCellDelegate
- (void)btnClickWithCell:(KKMusicPlayListCell *)cell Btn:(UIButton *)btn model:(nonnull XMTrack *)model
{
    
    
    if ([self getIndex] == cell.index && self.model.albumId == [ICMusicPlayManager sharedManager].albumModel.albumId) {
           if (_sdkPlayer.playerState == XMSDKPlayerStatePlaying) {
               [self pause];
           }else if (_sdkPlayer.playerState == XMSDKPlayerStatePaused){
               [self resume];
           }else if (_sdkPlayer.playerState == XMSDKPlayerStateStop){
               [self play:model];
           }
       }else {
           [self play:model];
       }
    

}

#pragma mark - 播放
- (void)play:(XMTrack *)track
{
    
    if(self.dataArray.count){
        [SVProgressHUD show];
        ICMusicPlayManager* manager = [ICMusicPlayManager sharedManager];
        manager.albumModel = self.model;
        manager.currentPage = currentPage;
        [[XMSDKPlayer sharedPlayer] setPlayMode:XMSDKPlayModeTrack];
        [[XMSDKPlayer sharedPlayer] setTrackPlayMode:XMTrackPlayerModeList];
        [[XMSDKPlayer sharedPlayer] playWithTrack:track playlist:self.dataArray];
        [[XMSDKPlayer sharedPlayer] setAutoNexTrack:YES];
    }
    

}

- (void)pause
{
    if(self.dataArray.count){
        [[XMSDKPlayer sharedPlayer] pauseTrackPlay];
    }
}
  
- (void)resume
{
    if (self.dataArray.count) {
        [[XMSDKPlayer sharedPlayer] resumeTrackPlay];
    }
}

-(void)stop
{
    if(self.dataArray.count){
        [[XMSDKPlayer sharedPlayer] stopTrackPlay];
    }
    
}

-(void)playPreTrack
{
    if(self.dataArray.count){
        [[XMSDKPlayer sharedPlayer] playPrevTrack];
    }
    
}

- (void)playNextTrack
{
    if(self.dataArray.count){
        [[XMSDKPlayer sharedPlayer] playNextTrack];
    }
}
#pragma mark - event response
- (void)backClick
{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)playBtnClick:(UIButton *)sender
{
    lastBtn = currentBtn;
    currentBtn = sender;
    
    NSInteger index = sender.tag - 200;
     XMTrack*model = self.dataArray[index];
    if (_selectIndex == sender.tag) {
        if (_sdkPlayer.playerState == XMSDKPlayerStatePlaying) {
            [self pause];
        }else if (_sdkPlayer.playerState == XMSDKPlayerStatePaused){
            [self resume];
        }else if (_sdkPlayer.playerState == XMSDKPlayerStateStop){
            [self play:model];
        }
    }else {
        [self play:model];
    }
    
    
    _selectIndex = sender.tag;
    //self.isPlaying = _sdkPlayer.playerState == XMSDKPlayerStatePlaying;
    [self.tableView reloadData];
}

- (void)tapClick:(UITapGestureRecognizer *)tap
{
    KKPlayerViewController* vc = [KKPlayerViewController new];
    
    [self.navigationController pushViewController:vc animated:YES];
}

- (BOOL)getPlayingState:(NSInteger)index
{
    if (self.isPlaying) {
        if (_selectIndex == (index + 200)) {
            return YES;
        }
    }
    return NO;
}



#pragma mark - 动画
- (void)startRotatingWithView:(UIView *)view
{
     CABasicAnimation* rotateAnimation = [CABasicAnimation animationWithKeyPath:@"transform.rotation"];
     rotateAnimation.fromValue = [NSNumber numberWithFloat:0.0];
     rotateAnimation.toValue = [NSNumber numberWithFloat:M_PI * 2];
    rotateAnimation.duration = 20;
    rotateAnimation.repeatCount = MAXFLOAT;
    [view.layer addAnimation:rotateAnimation forKey:nil];
}

//暂停动画
-(void)animationPauseWithView:(UIView *)view{
    //获取当前layer的动画媒体时间
    CFTimeInterval interval = [view.layer convertTime:CACurrentMediaTime() fromLayer:nil];
    //设置时间偏移量,保证停留在当前位置
    view.layer.timeOffset = interval;
    //暂定动画
    view.layer.speed = 0;
}
//恢复动画
-(void)animationResumeWithView:(UIView *)view{
    //获取暂停的时间
    CFTimeInterval beginTime = CACurrentMediaTime() - view.layer.timeOffset;
    //设置偏移量
    view.layer.timeOffset = 0;
    //设置开始时间
    view.layer.beginTime = beginTime;
    //开始动画
    view.layer.speed = 1;
}




#pragma mark - 获取到每一个cell的状态
- (void)setStatueWithAllData:(NSArray *)allDate CurrentIndex:(NSInteger)currentIndex {
    [_statueArray removeAllObjects];
    for (NSInteger i = 0; i < allDate.count; i++) {
        if (self.isPlaying) {
            if (currentIndex == i) {
                [_statueArray addObject:@"1"];
            }else {
                [_statueArray addObject:@"0"];
            }
        }else{
            [_statueArray addObject:@"0"];
        }
        
    }
}

#pragma mark - 获取当前播放音频的索引
- (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 - 添加浮动图
- (void)addArcImg:(XMTrack *)track
{
    if (track && self.iconImg == nil) {
           UIView*shadowView = [[UIView alloc]initWithFrame:CGRectMake(ScreenWidth - 70, ScreenHeight - 150, 50, 50)];
           self.shadowView = shadowView;
           _iconImg = [[UIImageView alloc]init];
           _iconImg.frame = CGRectMake(2, 2, 46, 46);
           _iconImg.layer.cornerRadius = 23;
           _iconImg.layer.masksToBounds = YES;
           _iconImg.userInteractionEnabled = YES;
           _iconImg.layer.borderWidth = 2;
           _iconImg.layer.borderColor = [UIColor colorWithWhite:1 alpha:0.5].CGColor;
           ProgressView*progressView = [[ProgressView alloc]initWithFrame:CGRectMake(0, 0, 50, 50)];
           self.progressView = progressView;
           progressView.width = 5;
           
           [self.view addSubview:shadowView];
           [shadowView addSubview:progressView];
           [shadowView addSubview:_iconImg];
           shadowView.layer.shadowColor = [UIColor blackColor].CGColor;

           shadowView.layer.shadowOffset = CGSizeMake(0, 0);

           shadowView.layer.shadowOpacity = 1;

           shadowView.layer.shadowRadius = 5.0;

           shadowView.layer.cornerRadius = 25.0;

           shadowView.clipsToBounds = NO;
           
           UITapGestureRecognizer*tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapClick:)];
           [_iconImg addGestureRecognizer:tap];
           
       }
       
       if (self.iconImg && track) {
           [_iconImg sd_setImageWithURL:[NSURL URLWithString:track.coverUrlLarge] placeholderImage:[UIImage imageNamed:@"trackPlaceImg"]];
       }
       
       if (_sdkPlayer.isPlaying && self.iconImg) {
           [self startRotatingWithView:self.iconImg];
       }
}

#pragma mark - 锁频控制
//更新通知中心控制台媒体信息
- (void)setupLockScreenMediaInfo:(XMTrack *)track {
    
    MPNowPlayingInfoCenter *playingCenter = [MPNowPlayingInfoCenter defaultCenter];
    
    NSMutableDictionary *playingInfo = [NSMutableDictionary new];
    //标题
    playingInfo[MPMediaItemPropertyTitle]      = track.trackTitle;
    //封面图片
    UIImage *coverImage = nil;
    if ([NSString blankString:track.coverUrlLarge]) {
        coverImage = [UIImage imageNamed:@"trackPlaceImg"];
    }else {
        UIImageView *coverImageView = [[UIImageView alloc] init];
        [coverImageView sd_setImageWithURL:[NSURL URLWithString:track.coverUrlSmall]];
        coverImage = coverImageView.image;
        if (coverImage == nil) {
            coverImage = [UIImage imageNamed:@"trackPlaceImg"];
        }
    }
    MPMediaItemArtwork *artwork = [[MPMediaItemArtwork alloc] initWithImage:coverImage];
    playingInfo[MPMediaItemPropertyArtwork] = artwork;
    
    // 当前播放的时间
    NSLog(@"playingInfo . currentTime = %f",track.duration / 1000.0);
    playingInfo[MPNowPlayingInfoPropertyElapsedPlaybackTime] = [NSNumber numberWithFloat:100 / 1000];
    // 进度的速度
    playingInfo[MPNowPlayingInfoPropertyPlaybackRate] = [NSNumber numberWithFloat:1.0];
    // 总时间
    playingInfo[MPMediaItemPropertyPlaybackDuration] = [NSNumber numberWithFloat:track.duration / 1000];
//    if (@available(iOS 10.0, *)) {
//        playingInfo[MPNowPlayingInfoPropertyPlaybackProgress] = [NSNumber numberWithFloat:self.audioControlView.progress];
//    } else {
//        // Fallback on earlier versions
//    }
    [playingCenter setNowPlayingInfo:playingInfo];
}


#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)getLabelHeightWithStr:(NSString *)str font:(UIFont *)font width:(CGFloat)width
{

    NSStringDrawingOptions options =  NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading;

    CGRect rect = [str boundingRectWithSize:CGSizeMake(width,MAXFLOAT) options:options attributes:@{NSFontAttributeName:font} context:nil];

    CGFloat realHeight = ceilf(rect.size.height);
    
    return realHeight;
}
#pragma mark - 获取播放状态并刷新UI
- (void)getPlayingStateAndRefreshUI
{
    if (_sdkPlayer.isPlaying) {
        self.playingState = XMSDKPlayerStatePlaying;
    }else if (_sdkPlayer.isPaused){
        self.playingState = XMSDKPlayerStatePaused;
    }else{
        self.playingState = XMSDKPlayerStateStop;
    }
    
    if ([ICMusicPlayManager sharedManager].albumModel.albumId == self.model.albumId) {
        self.isPlaying = YES;
    }else{
        self.isPlaying = NO;
    }
    [self setStatueWithAllData:self.dataArray CurrentIndex:[self getIndex]];
    
    [self.tableView reloadData];
    
    XMTrack*track = [_sdkPlayer currentTrack];
    
    
    
    [self addArcImg:track];
    
    if (self.isPlaying == NO || (self.playingState ==XMSDKPlayerStateStop)) {
           self.shadowView.hidden = YES;
       }else{
           if (self.shadowView) {
               self.shadowView.hidden = NO;
           }
           
           self.progressView.percent = track.listenedTime/(CGFloat)track.duration;
       }
}
#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 - 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
