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

#import "TrackHistoryController.h"
#import "TrackHistoryCell.h"
#import "KKXMHistoryTrackModel.h"
#import "XMSDK.h"

#import "KKPlayerViewController.h"

@interface TrackHistoryController ()<UITableViewDelegate,UITableViewDataSource>

@property (nonatomic, strong)UITableView* tableview;

@property (nonatomic, strong)NSArray* dataArray;

@end

@implementation TrackHistoryController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    [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];
}

- (void)loadData
{
    
    NSString *adId = [[[ASIdentifierManager sharedManager] advertisingIdentifier] UUIDString];
    NSString*phone = nil;
    if (![[NSUserDefaults standardUserDefaults] boolForKey:@"firstlog"]) {
        phone = adId;
    }else{
        phone = [EnercryTool encryptUseDES:[getPeopleID PeopleIphoneNmber] key:DESKEY];
    }
    
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    [params setObject:phone forKey:@"phone"];
    
    NSString*url = [NSString stringWithFormat:@"%@%@",[NetworkConfig ipXMLYHistoryConfig],XMLYListenTrackHistoryRequest];
    WeakSelf
    [NetworkRequest Post:url Params:params Success:^(id _Nonnull objc) {
        NSLog(@"objc:%@",objc);
        [SVProgressHUD dismiss];
        __strong typeof(self) strongSelf = weakSelf;
        [strongSelf.tableview.mj_header endRefreshing];
        
        NSString*state = [NSString stringWithFormat:@"%@",objc[@"state"]];
        NSString*describe = [NSString stringWithFormat:@"%@",objc[@"describe"]];
        if ([state isEqualToString:@"200"]) {
            strongSelf.dataArray = [KKXMHistoryTrackModel mj_objectArrayWithKeyValuesArray:objc[@"result"]];
            [strongSelf.tableview reloadData];
        }else{
            [SVProgressHUD showErrorWithStatus:describe];
        }
    } Failure:^(NSError* error) {
         __strong typeof(self) strongSelf = weakSelf;
        [SVProgressHUD dismiss];
        [strongSelf.tableview.mj_header endRefreshing];
        NSLog(@"error:%@",error);
        [SVProgressHUD showErrorWithStatus:@"网络异常"];
    }];
}




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

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    TrackHistoryCell* cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    
    KKXMHistoryTrackModel*model = self.dataArray[indexPath.section];
    
    cell.lb_title.text = model.listentitle;

    [cell.deleteBtn addTarget:self action:@selector(deleteClick:) forControlEvents:UIControlEventTouchUpInside];
    cell.deleteBtn.tag = indexPath.section;
    
    return cell;
}

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

- (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
{
    KKXMHistoryTrackModel*model = self.dataArray[indexPath.section];
     NSMutableDictionary *params = [NSMutableDictionary dictionary];
    [params setObject:model.trackid forKey:@"ids"];
    WeakSelf
    [SVProgressHUD show];
    [[XMReqMgr sharedInstance] requestXMData:XMReqType_TracksBatch params:params withCompletionHander:^(id result, XMErrorModel *error) {
        [SVProgressHUD dismiss];
        __strong typeof(self) strongSelf = weakSelf;
        if (!error){
           NSArray* array =  [strongSelf showReceivedData:result className:@"XMTrack" valuePath:@"tracks" titleNeedShow:@"trackTitle"];
            if (array.count > 0) {
                KKPlayerViewController*detailVC = [[KKPlayerViewController alloc]init];
                   
                detailVC.model = array[0];
                
                detailVC.dataArray = array;
                   
                   
                [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);
    }];
}


- (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)deleteClick:(UIButton *)sender
{
    NSString *adId = [[[ASIdentifierManager sharedManager] advertisingIdentifier] UUIDString];
    NSString*phone = nil;
    if (![[NSUserDefaults standardUserDefaults] boolForKey:@"firstlog"]) {
        phone = adId;
    }else{
        phone = [EnercryTool encryptUseDES:[getPeopleID PeopleIphoneNmber] key:DESKEY];
    }
    
    KKXMHistoryTrackModel*model = self.dataArray[sender.tag];
     NSMutableDictionary *params = [NSMutableDictionary dictionary];
     [params setObject:phone forKey:@"phone"];
     [params setObject:model.albumid forKey:@"albumid"];
    [params setObject:model.listenindex forKey:@"listenindex"];
        
     NSString*url = [NSString stringWithFormat:@"%@%@",[NetworkConfig ipXMLYHistoryConfig],DeleteXMLYListenTrackHistoryRequest];
    WeakSelf
    [SVProgressHUD show];
    [NetworkRequest Post10:url Params:params Success:^(id _Nonnull objc) {
        NSLog(@"objc:%@",objc);
        __strong typeof(self) strongSelf = weakSelf;
        NSString*state = [NSString stringWithFormat:@"%@",objc[@"state"]];
        NSString*describe = [NSString stringWithFormat:@"%@",objc[@"describe"]];
        if ([state isEqualToString:@"200"]) {
            [strongSelf loadData];
            return;
        }else{
            [SVProgressHUD dismiss];
            [SVProgressHUD showErrorWithStatus:describe];
        }
        
    } Failure:^(NSError* error) {
        NSLog(@"error:%@",error);
        [SVProgressHUD dismiss];
        [SVProgressHUD showErrorWithStatus:@"网络异常"];
    }];
}


#pragma mark - getters
- (UITableView *)tableview
{
    if (!_tableview) {
        _tableview = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, CGRectGetWidth(self.view.bounds), CGRectGetHeight(self.view.bounds)) style:UITableViewStyleGrouped];
       _tableview.showsVerticalScrollIndicator = NO;
        _tableview.delegate = self;
        _tableview.dataSource = self;
        _tableview.estimatedSectionHeaderHeight = 0;
        _tableview.backgroundColor = [UIColor colorWithHex:0xf4f4f4];
        [_tableview registerNib:[UINib nibWithNibName:@"TrackHistoryCell" 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
