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

#import "MyRankViewController.h"
#import "UserRankModel.h"
#import "MyRankTopTableCell.h"
#import "MyWalletRankHeaderView.h"
#import "MyWalletRankTableCell.h"

#import "LSLDecimalNumberTool.h"

#import "KKSVideoViewController.h"

//小满
#import <BXMediaSDK/BXMediaMaterialManager.h>
#import "KKActivityViewController.h"
#import "GuideONLineFindJobAlertView.h"


@interface MyRankViewController ()<UITableViewDelegate,UITableViewDataSource>

@property (nonatomic, strong)UITableView *tableView;

@property (nonatomic, strong)NSArray *dataArray;

@property (nonatomic, strong)UserRankModel *rankModel;

@end

@implementation MyRankViewController
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:YES animated:animated];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor colorWithHex:0xf4f4f4];
    
    [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 colorWithHex:0xf98505];
    //返回按钮
    UIButton* backBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [backBtn setTitle:@"返回" forState:UIControlStateNormal];
    [backBtn setImage:[UIImage imageNamed:@"返回"] forState:UIControlStateNormal];
    [backBtn setTitleColor:[UIColor whiteColor] 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 whiteColor];
    [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);
    }];
    
    
    [self.view addSubview:navView];
    
    [self creatBottomView];
}

- (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/getRanking",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 = [UserRankModel mj_objectWithKeyValues:responseObj[@"result"]];
                    [self.tableView reloadData];
                }
            }
            
        }];
    }
}


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

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        
        MyRankTopTableCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MyRankTopTableCell"];
        
        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 *sumProfit = [NSString stringWithFormat:@"%@",dic[@"userCurrentAccrue"]];
                if (![Tools isBlankString:sumProfit]) {
                    cell.lb_sumProfit.text = [NSString stringWithFormat:@"%@元",sumProfit];
                }
            }
            
        }
        

        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);
    
    RankUserModel *userModel = self.rankModel.rankList[indexPath.row];
    
    [cell.userIcon sd_setImageWithURL:[NSURL URLWithString:userModel.accountphoto]];
    if (![Tools isBlankString:userModel.cusname]) {
        cell.lb_nickName.text = userModel.cusname;
    }
    
    if (![Tools isBlankString:userModel.accumulatedmoney]) {
        cell.lb_profitSum.text =  [NSString stringWithFormat:@"%@元",[LSLDecimalNumberTool stringWithDecimalNumber:userModel.accumulatedmoney.doubleValue]];
    }
    
    return cell;
   
    
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (indexPath.section == 0) {
        return 200 * WIDTHRADIU;
    }
    
    return 66 * WIDTHRADIU;
}

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

        return headerView;
    }
    return nil;
}

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

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    if (section == 0) {
        return 10 * WIDTHRADIU;
    }
    
    return 0.0;
}

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


#pragma mark event response
- (void)backClick:(UIButton *)sender
{
    [self.navigationController popViewControllerAnimated:YES];
}
- (void)earnBtnClick:(UIButton *)sender
{
    NSInteger i = [UserDefault integerForKey:@"profitRankListEarnClickNum"];
    
    if (i == 0) {
        [self goToTVVC:NO];
    }else if (i == 1){
        [self loadXMImageData];
    }else if (i == 2){
        [self addRedPackage];
    }
    
    i++;
    if (i >= 3) {
        i = 0;
    }
    
    [UserDefault setInteger:i forKey:@"profitRankListEarnClickNum"];
    [UserDefault synchronize];
}

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


#pragma mark - 剪羊毛
- (void)loadXMImageData
{
//  __block NSString*adId = [[[ASIdentifierManager sharedManager] advertisingIdentifier] UUIDString];
    
    __weak typeof(self) weakSelf = self;
    [BXMediaMaterialManager getEntranceMaterialsWithAppkey:@"kksh-IOS-hdgj_xsekjn" placId:@"6668" thirdUserId:@"" success:^(BXMMaterialModel *model) {
        
        
        [BXMediaMaterialManager entranceShowEventTrackingWithPlaceId:@"6668" userId:@"" materialModel:model];
        
       
        [BXMediaMaterialManager entranceClickEventTrackingWithPlaceId:@"6668" userId:@"" materialModel:model];
        
        KKActivityViewController *vc = [KKActivityViewController new];
        vc.title = @"剪羊毛";
        vc.placeId = @"6668";
        vc.buId = @"946405771";
        vc.gdtAdId = @"2082218177897738";
        [weakSelf.navigationController pushViewController:vc animated:YES];
       
        
    } fail:^(NSString *error) {
    
        
    }];
}

#pragma mark - 天天领现金
- (void)addRedPackage
{
    //素材使用代码
   //素材曝光,一般在素材加载完成的时候调用.如果不知道素材加载好的时机,可以在素材所在页面加载完成的时候调用
//  __block NSString*adId = [[[ASIdentifierManager sharedManager] advertisingIdentifier] UUIDString];
   
   
   //加载素材
   //__weak typeof(self) weakSelf = self;
   [BXMediaMaterialManager getEntranceMaterialsWithAppkey:@"kksh-IOS-hdgj_xsekjn" placId:@"6667" thirdUserId:@"" success:^(BXMMaterialModel *model) {
       //weakSelf.model = model;
       if (model) {
           
           [BXMediaMaterialManager entranceShowEventTrackingWithPlaceId:@"6667" userId:@"" materialModel:model];
           
        
           [BXMediaMaterialManager entranceClickEventTrackingWithPlaceId:@"6667" userId:@"" materialModel:model];
           
           KKActivityViewController *vc = [KKActivityViewController new];
           vc.title = @"天天赚钱";
           vc.placeId = @"6667";
           vc.buId = @"946405763";
           vc.gdtAdId = @"9002117197798706";
           vc.hidesBottomBarWhenPushed = YES;
           [self.navigationController pushViewController:vc animated:YES];
           
           
           
       }
   } fail:^(NSString *error) {
       
   }];
}



#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:[MyRankTopTableCell class] forCellReuseIdentifier:@"MyRankTopTableCell"];
        [_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
