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

#import "AlbumHistoryController.h"
#import "MyAlbumHistoryTableViewCell.h"
#import "XMSDK.h"
#import "UIImageView+WebCache.h"
#import "KKXMHistoryAlbumModel.h"
#import "KKListenDetailController.h"

@interface AlbumHistoryController ()<UITableViewDelegate,UITableViewDataSource>

@property (nonatomic, strong)UITableView* tableview;

@property (nonatomic, strong)NSArray* dataArray;



@end

@implementation AlbumHistoryController

- (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],XMLYListenAlbumHistoryRequest];
    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 = [KKXMHistoryAlbumModel 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:@"网络异常"];
    }];
}

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

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

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    MyAlbumHistoryTableViewCell* cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    
    KKXMHistoryAlbumModel*model = self.dataArray[indexPath.section];
    
    [cell.img sd_setImageWithURL:[NSURL URLWithString:model.imageurl
                                  ] placeholderImage:[UIImage imageNamed:@""]];
    cell.lb_title.text = model.albumtitle;
    cell.lb_no.text = [NSString stringWithFormat:@"播放至%@集",model.pageindex];
    cell.lb_total.text = [NSString stringWithFormat:@"共%@集",model.allpageindex];
    
    [cell.deleteBtn addTarget:self action:@selector(deleteClick:) forControlEvents:UIControlEventTouchUpInside];
    cell.deleteBtn.tag = indexPath.section;
    
    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
{
    
    KKXMHistoryAlbumModel*model = self.dataArray[indexPath.section];
     NSMutableDictionary *params = [NSMutableDictionary dictionary];
    [params setObject:model.albumid 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)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];
    }
    
    KKXMHistoryAlbumModel*model = self.dataArray[sender.tag];
     NSMutableDictionary *params = [NSMutableDictionary dictionary];
     [params setObject:phone forKey:@"phone"];
     [params setObject:model.albumid forKey:@"albumid"];
        
     NSString*url = [NSString stringWithFormat:@"%@%@",[NetworkConfig ipXMLYHistoryConfig],DeleteXMLYListenAlbumHistoryRequest];
    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 - 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
- (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.backgroundColor = [UIColor colorWithHex:0xf4f4f4];
        _tableview.delegate = self;
        _tableview.dataSource = self;
        _tableview.estimatedSectionHeaderHeight = 0;
        [_tableview registerNib:[UINib nibWithNibName:@"MyAlbumHistoryTableViewCell" 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
