//
//  CoinsRankViewController.m
//  Open
//
//  Created by 雷俊博 on 2021/7/30.
//  Copyright © 2021 黄江涛 . All rights reserved.
//

#import "CoinsRankViewController.h"
#import "CoinsRankTopTableCell.h"
#import "CoinsRankMiddleTableCell.h"
#import "MyWalletRankTableCell.h"
#import "MyWalletRankHeaderView.h"

#import "CoinsDetailListVC.h"


#import "KKSVideoViewController.h"

#import "CoinsRankModel.h"

@interface CoinsRankViewController ()<UITableViewDelegate,UITableViewDataSource,UIScrollViewDelegate,CoinsRankTopTableCellDelegate>

@property (nonatomic, strong)UITableView *tableView;

@property (nonatomic, strong)NSArray *dataArray;

@property (nonatomic, strong)CoinsRankModel *rankModel;

@end

@implementation CoinsRankViewController
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    [self.navigationController setNavigationBarHidden:YES animated:animated];
    
    [self.tableView reloadData];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor whiteColor];

    [self.view addSubview:self.tableView];
    
    [self navConfig];
    
    [self loadRankListRequest];
}

- (void)navConfig
{
    UIView*navView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, cl_kNavigationBarHeight)];
    navView.backgroundColor = [UIColor whiteColor];
    //返回按钮
    UIButton* backBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [backBtn setTitle:@"返回" forState:UIControlStateNormal];
    [backBtn setImage:[UIImage imageNamed:@"blackBack"] forState:UIControlStateNormal];
    [backBtn setTitleColor:[UIColor colorWithHex:0x4d4d4d] forState:UIControlStateNormal];
    backBtn.frame = CGRectMake(10, cl_kStatusBarHeight, 60, 44);
    backBtn.titleLabel.font = [UIFont systemFontOfSize:15];
    [backBtn layoutButtonWithEdgeInsetsStyle:GLButtonEdgeInsetsStyleLeft imageTitleSpace:4];
    [backBtn addTarget:self action:@selector(backClick:) forControlEvents:UIControlEventTouchUpInside];
    
    
    UILabel* lb_title = [UILabel new];
    lb_title.text = self.title;
    lb_title.font = [UIFont boldSystemFontOfSize:18];
    lb_title.textAlignment = NSTextAlignmentCenter;
    lb_title.textColor = [UIColor colorWithHex:0x4d4d4d];
    [navView addSubview:backBtn];
    [navView addSubview:lb_title];
    [lb_title mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.offset(cl_kStatusBarHeight);
        make.centerX.equalTo(navView);
        make.height.offset(44);
    }];
    
//    //兑换按钮
//    UIButton* ExchangBtn = [UIButton buttonWithType:UIButtonTypeCustom];
//    [ExchangBtn setTitle:@"金币兑换" forState:UIControlStateNormal];
//    [ExchangBtn setTitleColor:[UIColor colorWithHex:0x4d4d4d] forState:UIControlStateNormal];
//    ExchangBtn.titleLabel.font = [UIFont systemFontOfSize:15];
//    ExchangBtn.frame = CGRectMake(ScreenWidth - 100, cl_kStatusBarHeight, 100, 44);
//    [ExchangBtn addTarget:self action:@selector(ExchangBtn:) forControlEvents:UIControlEventTouchUpInside];
//    [navView addSubview:ExchangBtn];
    
    [self.view addSubview:navView];
    
    [self creatBottomView];
}
//#pragma mark - 金币兑换
//- (void)ExchangBtn:(UIButton *)button{
//    //兑换
//    [[clickEvent instance] clickEventRooterVC:self Content:@"JBDH" menuName:@"金币兑换" ID:@"0"];
//    [NetworkRequest statisticsWithEventName:@"dialog_MyCoins_JBDH"];
//}
- (void)creatBottomView
{
    CGFloat bottomViewHeight = cl_kNavigationBarHeight > 64 ? 55 * WIDTHRADIU  : 44 * WIDTHRADIU;
    
    UIView *bottomView = [[UIView alloc]initWithFrame:CGRectMake(0, ScreenHeight - bottomViewHeight, ScreenWidth, bottomViewHeight)];
    [self.view addSubview:bottomView];
    
    UIButton *earnBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    earnBtn.frame = CGRectMake(0, 0, ScreenWidth, bottomViewHeight);
    [earnBtn setTitle:@"看视频赚金币" forState:UIControlStateNormal];
    [earnBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    earnBtn.titleLabel.font = [UIFont systemFontOfSize:15 * WIDTHRADIU];
    earnBtn.backgroundColor = [UIColor colorWithHex:0xf98505];
    [earnBtn addTarget:self action:@selector(earnBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    [bottomView addSubview:earnBtn];
    
}

#pragma mark - 刷新金币和金额数量
- (void)refreshCoins
{
    
    if ([getPeopleID PeopleID] && [getPeopleID PeopleIphoneNmber])
    {
        NSDictionary *params = @{
                                 @"userId":[NSNumber numberWithInteger:[getPeopleID PeopleID]],
                                 @"telephone": [EnercryTool encryptUseDES:[getPeopleID PeopleIphoneNmber] key:DESKEY]
                                 };
        NSString *url =[NSString stringWithFormat:@"%@score/getpersonintegrals",CoinsBaseUrl];
        [BaseNetManager POST2:url parameters:params completionHandler:^(id responseObj, NSError *error) {
            
            if (error) {
                [SVProgressHUD showInfoWithStatus:@"无网络"];
                return ;
            }
            if (responseObj) {
                NSString *code = [responseObj[@"code"] stringValue];
                if ([code isEqualToString:@"0"]) {
                    [getPeopleID getTotalCoins:responseObj[@"result"]];
                   
                   
                    [self.tableView reloadData];
                    
                    return ;
                }
            }
            
        
        }];
    }
}

#pragma mark - 获取排名列表数据接口

- (void)loadRankListRequest
{
    if ([getPeopleID PeopleID] && [getPeopleID PeopleIphoneNmber])
    {
        NSDictionary *params = @{
                                 @"userId":[NSNumber numberWithInteger:[getPeopleID PeopleID]],
                                 @"telephone": [EnercryTool encryptUseDES:[getPeopleID PeopleIphoneNmber] key:DESKEY]
                                 };
        NSString *url =[NSString stringWithFormat:@"%@userservice/getScoreRank",CoinsBaseUrl];
//        WeakSelf
        [BaseNetManager POST2:url parameters:params completionHandler:^(id responseObj, NSError *error) {
            
           
            if (responseObj) {
                
                
                NSString *code = [NSString stringWithFormat:@"%@",responseObj[@"code"]];
                
                
                if ([code isEqualToString:@"0"]) {
                    self.rankModel = [CoinsRankModel mj_objectWithKeyValues:responseObj[@"result"]];
                    [self.tableView reloadData];
                }
            }
            
        }];
    }
}


#pragma mark -  UIScrollViewDelegate
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    if (scrollView == self.tableView) {
        CGFloat offsetY = scrollView.contentOffset.y;
        NSLog(@"%f",offsetY);
        
        if (offsetY <= 0) {
            scrollView.contentOffset = CGPointMake(scrollView.contentOffset.x, 0);
        }
    }
}

#pragma mark - UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 3;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    
    if (section == 2) {
        if (self.rankModel.list.count > 0) {
            return self.rankModel.list.count;
        }else{
            return 1;
        }
    }
    
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
  
    if (indexPath.section == 0) {
        CoinsRankTopTableCell *cell = [tableView dequeueReusableCellWithIdentifier:@"CoinsRankTopTableCell"];
       
        cell.delegate = self;
        
        NSDictionary *dic = [getPeopleID totalCoins];
        
        [cell reloadDataWithData:dic];
        
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        
        return cell;
    }else if (indexPath.section == 1){
        
        CoinsRankMiddleTableCell *cell = [tableView dequeueReusableCellWithIdentifier:@"CoinsRankMiddleTableCell"];
        
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        
        NSURL *url = [getPeopleID PeoplePhoto];
        if (url) {
            [cell.userIcon sd_setImageWithURL:url placeholderImage:[UIImage imageNamed:@"my_information_headportrait_default"]];
        }else{
            cell.userIcon.image = [UIImage imageNamed:@"my_information_headportrait_default"];
        }
        if (self.rankModel) {
            if (![Tools isBlankString:self.rankModel.rankNo]) {
                cell.lb_rank.text = self.rankModel.rankNo;
            }
    
            if (![Tools isBlankString:self.rankModel.percentage]) {
    
                cell.lb_percent.attributedText = [self setupAttributeString:[NSString stringWithFormat:@"超越了%@的人",self.rankModel.percentage] rangeText:self.rankModel.percentage color:[UIColor colorWithHex:0xf98505] font:[UIFont boldSystemFontOfSize:14 * WIDTHRADIU]];
            }
            NSDictionary *dic = [getPeopleID totalCoins];
            if (dic) {
                NSString *currentTotalCoins = [NSString stringWithFormat:@"%@",dic[@"totalScore"]];
                NSString *expendScore = [NSString stringWithFormat:@"%@",dic[@"expendScore"]];
                
                NSString *sumProfit = [NSString stringWithFormat:@"%@",@(currentTotalCoins.integerValue + expendScore.integerValue)];
                if (![Tools isBlankString:sumProfit]) {
                    cell.lb_sumProfit.text = [NSString stringWithFormat:@"%@",sumProfit];
                }
            }
    
        }
        
        return cell;
        
    }
    
    if (self.rankModel.list.count == 0) {
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"emptyCell"];
        
        if (!cell) {
            cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"emptyCell"];
        }
        
        for (UIView *view in cell.contentView.subviews) {
            if (view.tag == 200) {
                [view removeFromSuperview];
                break;
            }
        }
        
        
        UILabel *lb_content = [UILabel new];
        lb_content.text = @"数据更新中";
        lb_content.textColor = [UIColor colorWithHex:0x808080];
        lb_content.textAlignment = NSTextAlignmentCenter;
        lb_content.font = [UIFont systemFontOfSize:17];
        [cell.contentView addSubview:lb_content];
        [lb_content mas_makeConstraints:^(MASConstraintMaker *make) {
            make.center.equalTo(cell.contentView);
        }];
        
        
        
        return cell;
    }
    
    
    MyWalletRankTableCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MyWalletRankTableCell"];
    
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    if (indexPath.row == 0) {
        cell.rankIcon.image = [UIImage imageNamed:@"coin_rank1"];
        cell.lb_rank.text = @"";
        cell.userIcon.layer.borderColor = [UIColor colorWithHex:0xffdf53].CGColor;
        cell.userIcon.layer.borderWidth = 2 * WIDTHRADIU;
    }else if (indexPath.row == 1){
        cell.rankIcon.image = [UIImage imageNamed:@"coin_rank2"];
        cell.lb_rank.text = @"";
        cell.userIcon.layer.borderWidth = 0;
    }else if (indexPath.row == 2){
        cell.rankIcon.image = [UIImage imageNamed:@"coin_rank3"];
        cell.lb_rank.text = @"";
        cell.userIcon.layer.borderWidth = 0;
    }else{
        cell.rankIcon.image = [UIImage imageNamed:@""];
        cell.lb_rank.text = [NSString stringWithFormat:@"%ld",indexPath.row];
        cell.userIcon.layer.borderWidth = 0;
    }
    
    cell.top1Icon.hidden = !(indexPath.row == 0);
    cell.fireworksImg.hidden = !(indexPath.row == 0);
    
    CoinsUserModel *userModel = self.rankModel.list[indexPath.row];

    [cell.userIcon sd_setImageWithURL:[NSURL URLWithString:userModel.accountphoto]];
    if (![Tools isBlankString:userModel.cusname]) {
        
        
        cell.lb_nickName.text = [EnercryTool decryptUseDES:userModel.cusname key:DESKEY];;
    }

    if (![Tools isBlankString:userModel.accumulated]) {
        cell.lb_profitSum.text =  userModel.accumulated;
    }
    
    return cell;
    
  
   
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (indexPath.section == 0) {
        return 267 * WIDTHRADIU;
    }else if (indexPath.section == 1){
        return 133 * WIDTHRADIU;
    }
    if (self.rankModel.list.count == 0) {
        CGFloat bottomViewHeight = cl_kNavigationBarHeight > 64 ? 55 * WIDTHRADIU  : 44 * WIDTHRADIU;
        CGFloat height = ScreenHeight - cl_kNavigationBarHeight - 437 * WIDTHRADIU - bottomViewHeight;
        return height;
    }
    
    return 66 * WIDTHRADIU;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    if (section == 2) {
        MyWalletRankHeaderView * headerView = [[MyWalletRankHeaderView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, 37 * WIDTHRADIU)];

        headerView.lb_profitSum.text = @"累计金币";
        
        return headerView;
    }
    
    return nil;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (section == 2) {
        return 37 * WIDTHRADIU;
    }
    return 0.0;
}

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

#pragma mark - CoinsRankTopTableCellDelegate
- (void)CoinsRankTopTableCellBtnClickWithIndex:(NSInteger)index
{
    [self goToCoinsListVC];//金币明细
}

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

#pragma mark - 金币明细
- (void)goToCoinsListVC
{
    CoinsDetailListVC *vc = [[CoinsDetailListVC alloc]init];
    vc.title = @"金币明细";
    vc.type = ListVCTypeCoinsDetail;
    [self.navigationController pushViewController:vc animated:YES];
}


#pragma mark - 跳转到小视频
- (void)goToTVVC:(BOOL)fromHome {
        
    KKSVideoViewController *oneVC = [[KKSVideoViewController alloc]initWithType:fromHome];
    oneVC.title = fromHome ?@"看视频" :@"红包视频";
    oneVC.view.backgroundColor = [UIColor whiteColor];
    oneVC.block = ^(BOOL success) {
      
        
    };
    
    [self.navigationController pushViewController:oneVC animated:YES];
}

#pragma mark - 自定义富文本
- (NSMutableAttributedString *)setupAttributeString:(NSString *)text rangeText:(NSString *)rangeText color:(UIColor *)color font:(UIFont *)font  {
    NSRange hightlightTextRange = [text rangeOfString:rangeText];
    NSMutableAttributedString *attributeStr = [[NSMutableAttributedString alloc] initWithString:text];
    if (hightlightTextRange.length > 0) {
        [attributeStr addAttribute:NSForegroundColorAttributeName
                                     value:color
                                     range:hightlightTextRange];
        [attributeStr addAttribute:NSFontAttributeName value:font range:hightlightTextRange];
        return attributeStr;
    }else {
        return [rangeText copy];
    }
}

#pragma mark - getters and setters
- (UITableView *)tableView
{
    if (!_tableView) {
        CGFloat bottomViewHeight = cl_kNavigationBarHeight > 64 ? 55 * WIDTHRADIU  : 44 * WIDTHRADIU;
        _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0,cl_kNavigationBarHeight, ScreenWidth, ScreenHeight - cl_kNavigationBarHeight - bottomViewHeight) style:UITableViewStyleGrouped];
        _tableView.showsVerticalScrollIndicator = NO;
        _tableView.dataSource = self;
        _tableView.delegate = self;
        _tableView.separatorStyle =  UITableViewCellSeparatorStyleNone;
        _tableView.backgroundColor = [UIColor colorWithHex:0xf4f4f4];
        
        _tableView.estimatedSectionFooterHeight = 10;
        _tableView.estimatedSectionHeaderHeight = 10;
        _tableView.estimatedRowHeight = 50;
        
        [_tableView registerClass:[CoinsRankTopTableCell class] forCellReuseIdentifier:@"CoinsRankTopTableCell"];
        [_tableView registerClass:[CoinsRankMiddleTableCell class] forCellReuseIdentifier:@"CoinsRankMiddleTableCell"];
        [_tableView registerClass:[MyWalletRankTableCell class] forCellReuseIdentifier:@"MyWalletRankTableCell"];
        
    }
    
    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
