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

#import "XMLYSleepViewController.h"
#import "XMSDK.h"
#import "KKListenSubCell.h"
#import "UIImageView+WebCache.h"
#import "KKListenDetailController.h"
#import "KKSleepModel.h"

@interface XMLYSleepViewController ()<UITableViewDelegate,UITableViewDataSource>

@property (nonatomic, strong)UITableView* tableView;

@property (nonatomic, strong)NSMutableArray* dataArray;

@end

@implementation XMLYSleepViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self navConfig];
    self.dataArray = [NSMutableArray array];
    [self.view addSubview:self.tableView];
    
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
           make.top.offset(cl_kNavigationBarHeight);
           make.left.bottom.right.offset(0);
       }];
    
    [self loadData];
}
- (void)navConfig
{
    [self.navigationController setNavigationBarHidden:YES];
    
    UIView*navView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, cl_kNavigationBarHeight)];
    navView.backgroundColor = K_MainColor;
    [self.view addSubview:navView];
    
    
    UIButton * backBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    backBtn.frame = CGRectMake( 10 * WIDTHRADIU, cl_kStatusBarHeight , 50, 44);
    backBtn.titleLabel.textAlignment =NSTextAlignmentLeft;
    [backBtn setTitle:@"返回" 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];
    [navView addSubview:backBtn];
    [backBtn layoutButtonWithEdgeInsetsStyle:GLButtonEdgeInsetsStyleLeft imageTitleSpace:3];
    
    
    
    
    //title
    UILabel* lb_title = [[UILabel alloc]init];
    lb_title.textColor = [UIColor whiteColor];
    lb_title.font = [UIFont boldSystemFontOfSize:17 * WIDTHRADIU];
    lb_title.textAlignment = NSTextAlignmentCenter;
    [navView addSubview:lb_title];
    
    lb_title.text = self.title;
    
    [lb_title mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(navView);
        make.height.offset(25);
        make.top.offset(cl_kStatusBarHeight + 9.5);
    }];
}


- (void)loadData
{
    NSDictionary*params = @{
        @"topic_id":@3,
        @"with_vip_content":@NO
    };
    __weak typeof(self) sself = self;
    [SVProgressHUD show];
    [[XMReqMgr sharedInstance]requestXMDataWithPath:@"assisted_sleep/cards" params:params completionHandler:^(id result, XMErrorModel *error) {
        [SVProgressHUD dismiss];
        __strong typeof(self) strongSelf = sself;
        [strongSelf.tableView.mj_header endRefreshing];

        if (!error){
            strongSelf.dataArray  =  [KKSleepModel mj_objectArrayWithKeyValuesArray:result];
            
             [strongSelf.tableView reloadData];

        }else {
           NSLog(@"Error: error_no:%ld, error_code:%@, error_desc:%@",(long)error.error_no, error.error_code, error.error_desc);
        }
    }];
}

- (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"];
    
    KKSleepModel*model = self.dataArray[indexPath.section];
    
    [cell.img sd_setImageWithURL:[NSURL URLWithString:model.card_cover_url
                                  ] placeholderImage:[UIImage imageNamed:@""]];
    cell.lb_title.text = model.card_title;
    
    cell.lb_subTitle.text = @"";
    cell.lb_count.text = [self getStrWithCount:model.play_count.integerValue];
    
    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
{
    KKSleepModel*model = self.dataArray[indexPath.section];
    if (!model.assisted_sleep_track) {
        [Tools showMessage:@"数据异常"];
        return;
    }
    
     NSMutableDictionary *params = [NSMutableDictionary dictionary];
    [params setObject:model.assisted_sleep_track.album_id forKey:@"ids"];
    WeakSelf
    [SVProgressHUD show];
    [[XMReqMgr sharedInstance] requestXMData:XMReqType_AlbumsBatch params:params withCompletionHander:^(id result, XMErrorModel *error) {
        [SVProgressHUD dismiss];
        __strong typeof(self) strongSelf = weakSelf;
        if (!error){
           NSArray* array =  [strongSelf showReceivedData:result className:@"XMAlbum" valuePath:@"albums" titleNeedShow:@"albumTitle"];
            if (array.count > 0) {
                KKListenDetailController*detailVC = [[KKListenDetailController alloc]init];
                   
                detailVC.model = array[0];
                   
                   
                [strongSelf.navigationController pushViewController:detailVC animated:YES];
            }
        }else
            NSLog(@"Error: error_no:%ld, error_code:%@, error_desc:%@",(long)error.error_no, error.error_code, error.error_desc);
    }];
}


#pragma mark - event response
- (void)backClick
{
    [self.navigationController popViewControllerAnimated:YES];
}


#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 registerNib:[UINib nibWithNibName:@"KKListenSubCell" bundle:nil] forCellReuseIdentifier:@"cell"];
        _tableView.estimatedSectionFooterHeight = 0;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        WeakSelf
        _tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
            __strong typeof(self) strongSelf = weakSelf;
            [strongSelf 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
