//
//  WithDrawViewController.m
//  Open
//
//  Created by 雷俊博 on 2019/7/8.
//  Copyright © 2019 黄江涛 . All rights reserved.
//

#import "WithDrawViewController.h"
#import "Constants.h"

#import "WithDrawCollectionViewCell.h"
#import "CoinsExchangeCollectionReusableView.h"
#import "WithDrawView.h"
#import "CoinsFooterView.h"
#import "WithDrawFooterView.h"
#import "WithDrawBindWXAlertView.h"
#import "OrderProgressViewController.h"

#import "CTAPIBaseManager.h"

//顶部cell
#import "WithDrawTopCell.h"
#import "WithDrawPayWayCell.h"
#import "WithDrawPayAmountSelectCell.h"
#import "WithDrawBottomMessageCell.h"


//存钱罐
#import "SaveTabBarController.h"
#import "LittleGoldHouseWebVC.h"
#import "MyAssetsController.h"
#import "KKCLFundViewController.h"

#import "WithDrawBannerCell.h"
#import "WithDrawMoreCreditCell.h"
#import "PrizeInfoCommitSuccessAlertView.h"
#define ColsSpace 10 * WIDTHRADIU
#define LeftSpace 20 * WIDTHRADIU
#define RowSpace 10 * WIDTHRADIU
@interface WithDrawViewController ()<UICollectionViewDelegate,UICollectionViewDataSource,WithDrawTopCellDelegate,WithDrawPayWayCellDelegate,WithDrawPayAmountSelectCellDelegate,UITableViewDelegate,UITableViewDataSource,UIScrollViewDelegate,WithDrawViewDelegate,WithDrawMoreCreditCellDelegate>
{
    int cashlevel;
}

@property (nonatomic, strong)UITableView* tableView;

@property (nonatomic, strong)UICollectionView *collectionView;

@property (nonatomic, strong)WithDrawView *headerView;

@property (nonatomic, strong)UIButton *btn_Withdraw;

@property (nonatomic, strong)NSMutableDictionary *bindWXDic;

@property (nonatomic, strong)NSArray *dataArray;

@property (nonatomic, assign)NSInteger payIndex;
@property (nonatomic, assign)NSInteger unitIndex;

@property (nonatomic, assign)BOOL firstWithDraw;

@property (nonatomic, strong) NSArray *PhoneInfoArr;

@end

@implementation WithDrawViewController
#pragma mark - life cycle
- (NSArray *)PhoneInfoArr{
    if (_PhoneInfoArr == nil) {
        _PhoneInfoArr = [NSArray array];
    }
    return _PhoneInfoArr;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    //init
    self.unitIndex = 0;
    cashlevel = 101101;
    self.firstWithDraw = YES;
    self.view.backgroundColor = [UIColor colorWithHex:0xf4f4f4];
    self.bindWXDic = [[NSMutableDictionary alloc]init];
    
    //add subview
    [self.view addSubview:self.tableView];
    [self.view addSubview:self.btn_Withdraw];
    [self navConfig];

    if (@available(iOS 11.0, *)) {
        self.tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    } else {
        self.automaticallyAdjustsScrollViewInsets = NO;
    }
    
  

    //判断微信是否绑定
    [self requestBindAPI];
    //判断是否第一次提现
    [self JudgeIsFirstWithDrawRequest];;
//
    
    //[self showWithDrawCQGAlertView];
    
    
    [self getPhoneInfo];
}
#pragma mark - 存钱罐弹框
- (void)showWithDrawCQGAlertView
{
    NSDate *oldTime = [[NSUserDefaults standardUserDefaults]objectForKey:@"WithDrawCQG"];
    if (oldTime && [self isSameDay:[NSDate date] date2:oldTime]) {
        return;
    }
    NSDate *oldDate = [NSDate date];
    [[NSUserDefaults standardUserDefaults]setObject:oldDate forKey:@"WithDrawCQG"];
    [[NSUserDefaults standardUserDefaults]synchronize];

    [NetworkRequest statisticsWithEventName:@"show_WithDraw_CQG"];
    [GuideAlertView showInWindowWithImageName:@"WithDrawCQG" Block:^(BOOL success) {
        [[clickEvent instance] clickEventRooterVC:self Content:@"homeThree4" menuName:@"存钱罐"];
        [NetworkRequest statisticsWithEventName:@"dialog_WithDraw_CQG"];
    }];
}
//判断是否同一天
- (BOOL)isSameDay:(NSDate*)date1 date2:(NSDate*)date2
{
    NSCalendar* calendar = [NSCalendar currentCalendar];
    unsigned unitFlags = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit;
    NSDateComponents* comp1 = [calendar components:unitFlags fromDate:date1];
    NSDateComponents* comp2 = [calendar components:unitFlags fromDate:date2];
    return [comp1 day] == [comp2 day] &&
    [comp1 month] == [comp2 month] &&
    [comp1 year] == [comp2 year];
}
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:YES animated:animated];
    NSLog(@"viewwill");
//   self.navigationController.navigationBar.barTintColor = [UIColor colorWithHex:0xf98505];
//
//    [self.transitionCoordinator animateAlongsideTransition:^(id<UIViewControllerTransitionCoordinatorContext>  _Nonnull context) {
//        self.navigationController.navigationBar.barTintColor = [UIColor colorWithHex:0xf98505];
//    } completion:^(id<UIViewControllerTransitionCoordinatorContext>  _Nonnull context) {
//    }];
//    
//    self.navigationController.navigationBar.translucent = NO;
    
    [GTCountSDK trackCountEvent:@"life_tixianCenter" withArgs:@{}];//个推统计
}
- (void)viewWillLayoutSubviews
{
    [super viewWillLayoutSubviews];
//    [self.collectionView mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.top.offset(cl_kNavigationBarHeight);
//        make.left.right.offset(0);
//        make.bottom.offset(-45 * WIDTHRADIU);
//    }];
    [self.btn_Withdraw mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.bottom.offset(0);
        make.height.offset(45 * WIDTHRADIU);
    }];
}


- (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 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:17];
    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];
}


#pragma mark - api 调用
//查询是否绑定了微信
- (void)requestBindAPI
{
    
    WeakSelf
    NSString *url = [NSString stringWithFormat:@"%@scorepay/validateBind",CoinsBaseUrl];
    
    NSDictionary *dic = @{
                          @"userid":[NSNumber numberWithInteger:[getPeopleID PeopleID]],
                          @"telephone": [EnercryTool encryptUseDES:[getPeopleID PeopleIphoneNmber] key:DESKEY],
                          @"requestTimeStamp":[NSNumber numberWithInteger:[self getNowTimeTimestamp3]],
                          @"fromModel":@"2",
                          @"accounttype":[NSNumber numberWithInt:1],
                          };
    
    
    NSArray *result = [dic.allKeys sortedArrayUsingComparator:^NSComparisonResult(id  _Nonnull obj1, id  _Nonnull obj2) {
        
        NSLog(@"%@~%@",obj1,obj2); //3~4 2~1 3~1 3~2
        
        return [obj1 compare:obj2]; //升序
        
    }];
    NSString *sign = nil;
    for (int i = 0; i < result.count; i++) {
        NSString *key = result[i];
        if (i==0) {
            sign = [NSString stringWithFormat:@"%@=%@",key,dic[key]];
        }else{
            
            sign = [NSString stringWithFormat:@"%@&%@=%@",sign,key,dic[key]];
        }
    }
    
    sign = [NSString stringWithFormat:@"%@&weface9578",sign];
    
    NSMutableDictionary *params = [[NSMutableDictionary alloc]initWithDictionary:dic];
    
    NSString *signString = [[MyMD5 md5:sign] lowercaseString];
    [params setObject:signString forKey:@"sign"];
    [params setObject:@"506" forKey:@"appIdType"];
    [params setObject:@"kklife" forKey:@"terminal"];
    
    [CTAPIBaseManager POST:url params:params completionHandler:^(id  _Nonnull responseObject, NSError * _Nonnull error) {
        
        if (error) {
            [SVProgressHUD showInfoWithStatus:@"无网络"];
            return ;
        }
        
        if (responseObject) {
            NSNumber *code = responseObject[@"code"];
            NSString *des = responseObject[@"des"];
            if ([code isKindOfClass:[NSNumber class]]) {
                if (code.integerValue == 0) {
                   
                    [weakSelf.bindWXDic setValue:responseObject[@"result"][@"iconUrl"] forKey:@"iconUrl"];
                    [weakSelf.bindWXDic setValue:responseObject[@"result"][@"screenName"] forKey:@"screenName"];
                    //[weakSelf.collectionView reloadData];
                    NSMutableIndexSet *indexset = [[NSMutableIndexSet alloc]init];
                    [indexset addIndex:1];
                    [weakSelf.tableView reloadSections:indexset withRowAnimation:UITableViewRowAnimationNone];
                    
                }else{
                    [SVProgressHUD showInfoWithStatus:des];
                }
            }else{
                [SVProgressHUD showInfoWithStatus:@"服务器异常"];
            }
        }
    }];
}

#pragma mark - 判断是否第一次提现
- (void)JudgeIsFirstWithDrawRequest
{
    NSString *url = [NSString stringWithFormat:@"%@scorePayService/validateCashRecord",CoinsBaseUrl];
    
    NSDictionary *params = @{
        @"userId":[NSNumber numberWithInteger:[getPeopleID PeopleID]],
        @"telephone": [EnercryTool encryptUseDES:[getPeopleID PeopleIphoneNmber] key:DESKEY]
    };
    
    NSLog(@"判断是否第一次提现:%@",url);
    NSLog(@"params:%@",params);
    
    [CTAPIBaseManager POST:url params:params completionHandler:^(id  _Nonnull responseObject, NSError * _Nonnull error) {
       
        if (error) {
            NSLog(@"error:%@",error);
            return;
        }
        
        NSLog(@"responseObject:%@",responseObject);
        if ([responseObject isKindOfClass:[NSDictionary class]]) {
            NSString *code = [NSString stringWithFormat:@"%@",responseObject[@"code"]];
            if ([code isEqualToString:@"1071"]) {
                self.firstWithDraw = NO;
                self.unitIndex = 1;
                self->cashlevel = 101102;
            }else if ([code isEqualToString:@"1070"]) {
                self.firstWithDraw = YES;
                self.unitIndex = 0;
                self->cashlevel = 101101;
            }else {
                self.firstWithDraw = NO;
                self.unitIndex = 1;
                self->cashlevel = 101102;
            }
            
            [self.tableView reloadRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:0 inSection:1]] withRowAnimation:UITableViewRowAnimationNone];
        }
        
        
    }];
    
}


#pragma mark - UIScrollViewDelegate
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    CGFloat y = scrollView.contentOffset.y;
    if (y <= 0) {
        scrollView.contentOffset = CGPointMake(0, 0);
    }
}

#pragma mark - UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 3;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{

    
    if (indexPath.section == 0) {
        WithDrawTopCell* cell = [WithDrawTopCell cellWithTableView:tableView];
        
        cell.delegate = self;
        
        cell.backgroundColor = [UIColor colorWithHex:0xf98505];
        
        [cell refreshData];
        
        return cell;
    }else if(indexPath.section == 1){
        WithDrawPayAmountSelectCell* cell = [WithDrawPayAmountSelectCell cellWithTableView:tableView];
        
        cell.delegate = self;
        
        cell.binddelegate = self;
        if (self.bindWXDic.allKeys.count > 0) {
            [cell refreshUIWithDic:self.bindWXDic];
        }
        [cell reloadCellCollectViewWithIndex:self.unitIndex firstWithDraw:self.firstWithDraw];
        
        return cell;
    }
//    else if(indexPath.section == 2){
//        WithDrawMoreCreditCell* cell = [WithDrawMoreCreditCell cellWithTableView:tableView];
//        cell.delegate = self;
//        if (self.PhoneInfoArr.count > 0) {
//            cell.dataArray = self.PhoneInfoArr;
//        }
//        return cell;
//    }
    
    WithDrawBottomMessageCell *cell = [WithDrawBottomMessageCell cellWithTableView:tableView];
    
    return cell;
   
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        return 104 * WIDTHRADIU;
    }else if(indexPath.section == 1){
//        return 175 * WIDTHRADIU;
        return 150 * WIDTHRADIU;
    }else if(indexPath.section == 2){
        return 120*WIDTHRADIU;
    }
    return 230 * WIDTHRADIU;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if (section == 2) {
        return 50;
    }
    return 0.00001;
}
 
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    
//    if (section == 3) {
//        return 0;
//    }
//    return 10 * WIDTHRADIU;
    return 0.0;
}
 
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    if (section == 2) {
        UIView *headView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, 50)];
        headView.backgroundColor = [UIColor whiteColor];
        
        UIImageView *itemImg = [[UIImageView alloc]initWithFrame:CGRectMake(20,0, 17, 18)];
        itemImg.centerY = headView.centerY;
        [headView addSubview:itemImg];
        
        UILabel *titleLab = [[UILabel alloc]initWithFrame:CGRectMake(45, 0, ScreenWidth - 65, 50)];
        titleLab.font = [UIFont boldSystemFontOfSize:16.0];
        titleLab.textColor = [UIColor colorWithHex:0x4d4d4d];;
        [headView addSubview:titleLab];
//        if (section == 2) {
//            itemImg.image = [UIImage imageNamed:@"exchangeItem"];
//            titleLab.text = @"兑换商品";
//        }else
        if(section == 2){
            //itemImg.image = [UIImage imageNamed:@"MoreCreditItem"];
            //titleLab.text = @"话费充值";
        }
        return headView;
    }
    UIView *headView = [[UIView alloc]init];
    headView.backgroundColor = [UIColor whiteColor];
    return headView;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
//    if (indexPath.section == 2) {
//        [[clickEvent instance] clickEventRooterVC:self Content:@"JBDH" menuName:@"金币兑换" ID:@"0"];
//        [NetworkRequest statisticsWithEventName:@"dialog_WithDrawBanner_JBDH"];
//    }
}

#pragma mark - UICollectionViewDataSource
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return 2;
}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    if (section == 0) {
        return 1;
    }
    return self.dataArray.count;
}
- (__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    WithDrawCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cell" forIndexPath:indexPath];
    if (indexPath.section == 0) {
        cell.hiddenImg = YES;
        
        if (self.payIndex == indexPath.row) {
            cell.cellSelected = YES;
        }else{
            cell.cellSelected = NO;
        }
    }else{
        cell.hiddenImg = NO;
        NSNumber *money = self.dataArray[indexPath.row];
        cell.lb_money.text = [NSString stringWithFormat:@"%d元",money.intValue];
        if (self.unitIndex == indexPath.row) {
                   cell.cellSelected = YES;
               }else{
                   cell.cellSelected = NO;
               }
    }
    return cell;
}
//创建头视图
- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView
           viewForSupplementaryElementOfKind:(NSString *)kind
                                 atIndexPath:(NSIndexPath *)indexPath {
    if ([kind isEqualToString:UICollectionElementKindSectionHeader]) {
        CoinsExchangeCollectionReusableView *headView = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader
                                                                                           withReuseIdentifier:@"headerCell"
                                                                                                  forIndexPath:indexPath];
        if (indexPath.section == 0) {
             headView.lb_title.text = @"提现方式";
        }else if (indexPath.section == 1){
             headView.lb_title.text = @"提现金额";
        }
       
        return headView;
    }
  
        if ([kind isEqualToString:UICollectionElementKindSectionFooter]) {
            if (indexPath.section == 0) {
                WithDrawFooterView *footerView = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:@"WithDrawFooterView" forIndexPath:indexPath];
                footerView.delegate = self;
                if (self.bindWXDic.allKeys.count > 0) {
                    [footerView refreshUIWithDic:self.bindWXDic];
                }
                
                return footerView;
            }
            if (indexPath.section == 1) {
                CoinsFooterView *footerView = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:@"footerCell" forIndexPath:indexPath];
                footerView.lb_title.text = @"提现说明";
                
                NSString *text1 = @"1、由于微信支付要求实名制，非实名用户账号无法支持提现，\n请务必将提现的微信号进行实名认证！\n";
                NSString *text2 = @"2、每日提现总额受微信限制，若当日限额已满，请次日申请。\n";
                NSString *text3 = @"3、每日最多申请提现两次，提现申请将在两个小时内审核到账\n（如遇高峰期，可能延迟到账），请耐心等待。\n";
                
                NSMutableParagraphStyle * paragraphStyle = [[NSMutableParagraphStyle alloc] init];
                [paragraphStyle setLineSpacing:8];
                
                NSMutableAttributedString *attributedString1 = [[NSMutableAttributedString alloc] initWithString:text1 attributes:@{NSParagraphStyleAttributeName: paragraphStyle}];
                NSMutableAttributedString *attributedString2 = [[NSMutableAttributedString alloc] initWithString:text2 attributes:@{NSParagraphStyleAttributeName: paragraphStyle}];
                NSMutableAttributedString *attributedString3 = [[NSMutableAttributedString alloc] initWithString:text3 attributes:@{NSParagraphStyleAttributeName: paragraphStyle}];
                [attributedString1 appendAttributedString:attributedString2];
                [attributedString1 appendAttributedString:attributedString3];
                
                NSRange range = [[[text1 stringByAppendingString:text2] stringByAppendingString:text3] rangeOfString:[[text1 stringByAppendingString:text2] stringByAppendingString:text3]];
                [attributedString1 addAttributes:@{NSForegroundColorAttributeName:[UIColor colorWithHex:0x999999],
                                                   NSFontAttributeName:[UIFont systemFontOfSize:12 * WIDTHRADIU]} range:range];
                footerView.lb_content.attributedText = attributedString1;
                
                return footerView;
            }
           
        }
    
    
    return nil;
}

/**
 cell的大小
 */
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    
    
    CGFloat width = (CGRectGetWidth(collectionView.bounds) - (3 - 1) * ColsSpace - LeftSpace * 2)  / 3;
    CGFloat height = 40 * WIDTHRADIU;
    CGSize size = CGSizeMake(width, height);
    return size;
}
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout referenceSizeForFooterInSection:(NSInteger)section{
    
    if (section == 0) {
        return CGSizeMake(ScreenWidth, 45 * WIDTHRADIU);
    }else if (section == 1){
        return CGSizeMake(ScreenWidth, 240 * WIDTHRADIU);
    }
    return CGSizeZero;
}
/**
 每个分区的内边距（上左下右）
 */
- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section{
    return UIEdgeInsetsMake(0, LeftSpace, RowSpace + 5 * WIDTHRADIU, LeftSpace);
}
/**
 分区内cell之间的最小行间距
 */
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section{
    
    return RowSpace;
}
/**
 分区内cell之间的最小列间距
 */
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section{
    return 0.0;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 1) {
        if (indexPath.row == self.unitIndex) {
            return;
        }else{
            self.unitIndex = indexPath.row;
            [self.collectionView reloadData];
            
            if (indexPath.row  == 0) {
                cashlevel = 101101;
            }else if (indexPath.row == 1){
                cashlevel = 101102;
            }else if (indexPath.row == 2){
                cashlevel = 101103;
            }
        }
    }
}
#pragma mark - WithDrawMoreCreditCellDelegate 话费充值
- (void)MoreCreditIndex:(NSInteger)index{
    //话费充值
    if (self.PhoneInfoArr.count > 0) {
        NSDictionary *dic = self.PhoneInfoArr[index];
        WebVC *webvc = [[WebVC alloc]init];
        webvc.url = dic[@"url"];
        webvc.title = @"话费充值";
        webvc.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:webvc animated:YES];
    }
}
#pragma mark - WithDrawTopCellDelegate
- (void)clickEarnMoneyBtnClickWithCell:(WithDrawTopCell *)cell
{
    NSLog(@"点击灵活理财按钮");
//    [self judgeSaveAmountRequest];
    [[clickEvent instance] clickEventRooterVC:self Content:@"homeThree4" menuName:@"存钱罐"];
}

#pragma mark - WithDrawViewDelegate
- (void)bindWXWithCell:(WithDrawPayWayCell *)cell
{
    if (![[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:@"wechat://"]] ) {
       [SVProgressHUD showErrorWithStatus:@"您未安装微信\n只支持微信提现哟!"];
       
       return;
    }
           
    [self getUserInfoForPlatform:UMSocialPlatformType_WechatSession];
}

#pragma mark - WithDrawPayAmountSelectCellDelegate
- (void)clickCellWithIndex:(NSInteger)index
{
    
    self.unitIndex = index;
    
//    if (index  == 0) {
//        cashlevel = 101101;
//    }else if (index == 1){
//        cashlevel = 101102;
//    }else if (index == 2){
//        cashlevel = 101103;
//    }else if (index == 3){
//        cashlevel = 101104;
//    }else if (index == 4){
//        cashlevel = 101105;
//    }else if (index == 5){
//        cashlevel = 101106;
//    }
    if (index  == 0) {
        cashlevel = 101101;
    }else if (index == 1){
        cashlevel = 101102;
    }else if (index == 2){
        cashlevel = 101104;
    }
}


#pragma mark - 绑定微信
- (void)getUserInfoForPlatform:(UMSocialPlatformType)platformType
{WeakSelf
    [[UMSocialManager defaultManager] getUserInfoWithPlatform:platformType currentViewController:self completion:^(id result, NSError *error) {
        NSLog(@">>>>>wx>>result:%@, error:%@",result,error);
        
        if (error) {
            [SVProgressHUD showErrorWithStatus:@"微信授权失败!"];
            return;
        }
        
        UMSocialUserInfoResponse *resp = result;
        if(resp.uid ){
            if (!resp.name) {
                resp.name =@"";
            }
            if (!resp.iconurl) {
                resp.iconurl=@"";
            }
        }
        // 第三方登录数据(为空表示平台未提供)
        // 授权数据
        NSLog(@" uid: %@", resp.uid);//uuid
        NSLog(@" openid: %@", resp.openid);
        NSLog(@" accessToken: %@", resp.accessToken);
        NSLog(@" refreshToken: %@", resp.refreshToken);
        NSLog(@" expiration: %@", resp.expiration);
        
        // 用户数据
        NSLog(@" name: %@", resp.name);
        NSLog(@" iconurl: %@", resp.iconurl);
        NSLog(@" gender: %@", resp.gender);
        
        // 第三方平台SDK原始数据
        NSLog(@" originalResponse: %@", resp.originalResponse);
        
        NSDictionary *dic = @{
                              @"iconurl":resp.iconurl ? resp.iconurl :@"",
                              @"openid":resp.openid ? resp.openid : @"",
                              @"uid":resp.uid ? resp.uid : @"",
                              @"token":resp.accessToken ? resp.accessToken : @"",
                              @"screenname":resp.name ? resp.name : @"",
                              };
        [weakSelf bindWxApiWithParams:dic];
    }];
}

- (void)bindWxApiWithParams:(NSDictionary *)dic
{
    NSString *url = [NSString stringWithFormat:@"%@scorepay/accountBind",CoinsBaseUrl];

    NSDictionary *dic2 = @{
                          @"userid":[NSNumber numberWithInteger:[getPeopleID PeopleID]],
                          @"telephone": [EnercryTool encryptUseDES:[getPeopleID PeopleIphoneNmber] key:DESKEY],
                          @"accounttype":[NSNumber numberWithInt:1],
                          @"requestTimeStamp":[NSNumber numberWithInteger:[self getNowTimeTimestamp3]],
                          @"fromModel":@"2",
//                          @"accounttype":[NSNumber numberWithInt:1],
                          };
    
    NSMutableDictionary *dic3 = [[NSMutableDictionary alloc]initWithDictionary:dic];
    
    [dic3 addEntriesFromDictionary:dic2];
    
    
    NSArray *result = [dic3.allKeys sortedArrayUsingComparator:^NSComparisonResult(id  _Nonnull obj1, id  _Nonnull obj2) {
        
        NSLog(@"%@~%@",obj1,obj2); //3~4 2~1 3~1 3~2
        
        return [obj1 compare:obj2]; //升序
        
    }];
    NSString *sign = nil;
    for (int i = 0; i < result.count; i++) {
        NSString *key = result[i];
        if (i==0) {
            sign = [NSString stringWithFormat:@"%@=%@",key,dic3[key]];
        }else{
            
            sign = [NSString stringWithFormat:@"%@&%@=%@",sign,key,dic3[key]];
        }
    }
    
    sign = [NSString stringWithFormat:@"%@&weface9578",sign];
    
    NSMutableDictionary *params = [[NSMutableDictionary alloc]initWithDictionary:dic3];
    
    NSString *signString = [[MyMD5 md5:sign] lowercaseString];
    [params setObject:signString forKey:@"sign"];
    [params setObject:@"506" forKey:@"appIdType"];
    [params setObject:@"kklife" forKey:@"terminal"];
    
    NSString *username = dic3[@"screenname"];
    [params setObject:[username stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLPathAllowedCharacterSet]] forKey:@"screenname"];
    
    WeakSelf
    [CTAPIBaseManager POST:url params:params completionHandler:^(id  _Nonnull responseObject, NSError * _Nonnull error) {
        
        if (error) {
            [SVProgressHUD showInfoWithStatus:@"无网络"];
            return ;
        }
        
        if (responseObject) {
            NSNumber *code = responseObject[@"code"];
            NSString *des = responseObject[@"des"];
            if ([code isKindOfClass:[NSNumber class]]) {
                if (code.integerValue == 0) {
                    [weakSelf.bindWXDic setValue:dic[@"iconurl"] forKey:@"iconUrl"];
                    [weakSelf.bindWXDic setValue:dic[@"screenname"] forKey:@"screenName"];
                    NSMutableIndexSet *indexset = [[NSMutableIndexSet alloc]init];
                    [indexset addIndex:1];
                    [weakSelf.tableView reloadSections:indexset withRowAnimation:UITableViewRowAnimationNone];
                }else if (code.integerValue == 1019){
                     [SVProgressHUD showInfoWithStatus:@"该微信号已绑定"];
                }else{
                    [SVProgressHUD showInfoWithStatus:des];
                }
            }else{
                [SVProgressHUD showInfoWithStatus:@"服务器错误"];
            }
        }
    }];
}

//提现
- (void)loadWalletApi{
    
     WeakSelf
    //网络请求1
            if ([getPeopleID PeopleID]){
                 NSDictionary *dic = @{
                                         @"userid":[NSNumber numberWithInteger:[getPeopleID PeopleID]],
                                         @"telephone": [EnercryTool encryptUseDES:[getPeopleID PeopleIphoneNmber] key:DESKEY],
                                         @"requestTimeStamp":[NSNumber numberWithInteger:[self getNowTimeTimestamp3]],
                                         @"paystyle":@1,
                                         @"cashlevel":[NSNumber numberWithInt:cashlevel]
                                         };
                   
                   NSArray *result = [dic.allKeys sortedArrayUsingComparator:^NSComparisonResult(id  _Nonnull obj1, id  _Nonnull obj2) {
                       
                       NSLog(@"%@~%@",obj1,obj2); //3~4 2~1 3~1 3~2
                       
                       return [obj1 compare:obj2]; //升序
                       
                   }];
                   NSString *sign = nil;
                   for (int i = 0; i < result.count; i++) {
                       NSString *key = result[i];
                       if (i==0) {
                           sign = [NSString stringWithFormat:@"%@=%@",key,dic[key]];
                       }else{
                           
                           sign = [NSString stringWithFormat:@"%@&%@=%@",sign,key,dic[key]];
                       }
                   }
                   sign = [NSString stringWithFormat:@"%@&kw#8ra",sign];
                   NSMutableDictionary *params = [[NSMutableDictionary alloc]initWithDictionary:dic];
                   NSString *signString = [[MyMD5 md5:sign] lowercaseString];
                   [params setObject:signString forKey:@"sign"];
                [params setObject:@"506" forKey:@"appIdType"];
                [params setObject:@"kklife" forKey:@"terminal"];
                NSString *url =[NSString stringWithFormat:@"%@scorepay/cashtowall",CoinsBaseUrl];
                
               [SVProgressHUD show];          
                [BaseNetManager POST2:url parameters:params completionHandler:^(id responseObj, NSError *error) {
                    [SVProgressHUD dismiss];
                    if (error) {
                        [SVProgressHUD showInfoWithStatus:@"无网络"];
                        return ;
                    }
                    if (responseObj) {
                        if ([responseObj[@"code"] isKindOfClass:[NSNumber class]]) {
                            NSNumber *code = (NSNumber *)responseObj[@"code"];
//                            1011 账户无效  1018 账户未绑定  1029提现级别不存在 1030 提现金额不足  0 提现成功 1017 兑换失败 9999 系统异常
                            if (code.integerValue == 0) {
                                //[SVProgressHUD showSuccessWithStatus:@"提现成功!"];
                                //[weakSelf goToTiXianVCWithresult:YES];
                                [PrizeInfoCommitSuccessAlertView showReceiveViewWithVC:self  block:^(CTShareType type) {
                                    
                                }];
                                
                                if (self.block) {
                                    self.block(YES);
                                }

                                [weakSelf loadCoinsApi];
                            }else{
                                [SVProgressHUD showInfoWithStatus:@"提现失败"];
                                //[weakSelf goToTiXianVCWithresult:NO];
                            }
                        }else{
                            [SVProgressHUD showInfoWithStatus:@"服务端异常"];
                        }
                        
                    }
                }];
            }
    
        
             
             
             
    
}

- (void)loadCoinsApi
{
    WeakSelf
    //网络请求2
            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 (responseObj) {

                        if ([responseObj[@"code"] isKindOfClass:[NSNumber class]]) {
                            NSNumber *code = (NSNumber *)responseObj[@"code"];
                            if (code.integerValue == 0) {
                                [getPeopleID getTotalCoins:responseObj[@"result"]];
                                [weakSelf.headerView refreshData];
                            }
                        }
                        
                    }
                }];
            }
}



#pragma mark - event response
- (void)btnClick:(UIButton *)sender
{
    
    if (self.bindWXDic.allValues.count == 0) {
        WeakSelf
        [WithDrawBindWXAlertView showAlertViewWithBlock:^{
            [weakSelf bindWXWithCell:nil];
        }];
        
        return;
    }
    
    NSDictionary *dic = [getPeopleID totalCoins];
     
    NSNumber *currentotalProfit = dic[@"currentotalProfit"];
    
    NSNumber *unitMoney = self.dataArray[_unitIndex];
    if ([currentotalProfit isKindOfClass:[NSNumber class]]) {
        if (currentotalProfit.doubleValue < unitMoney.doubleValue) {
            [SVProgressHUD showInfoWithStatus:@"余额不足"];
            return;
        }
        
        [self loadWalletApi];
        
        
        
    }else{
        [SVProgressHUD showInfoWithStatus:@"数据异常"];
    }
  
}

- (void)goToTiXianVCWithresult:(BOOL)success{
    OrderProgressViewController *vc = [[OrderProgressViewController alloc]init];
    vc.title = @"提现结果";
    vc.dateStr = [self getCurrentDate];
    vc.success = success;
    [self.navigationController pushViewController:vc animated:YES];
}

- (void)backClick:(UIButton *)sender{
    [self.navigationController popViewControllerAnimated:YES];
}


#pragma mark - private methods
#pragma mark - 获取当前时间戳

-(NSInteger )getNowTimeTimestamp3{
    
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init] ;
    
    [formatter setDateStyle:NSDateFormatterMediumStyle];
    
    [formatter setTimeStyle:NSDateFormatterShortStyle];
    
    [formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss SSS"]; // ----------设置你想要的格式,hh与HH的区别:分别表示12小时制,24小时制
    
    //设置时区,这个对于时间的处理有时很重要
    
    NSTimeZone* timeZone = [NSTimeZone timeZoneWithName:@"Asia/Beijing"];
    
    [formatter setTimeZone:timeZone];
    
    NSDate *datenow = [NSDate date];//现在时间,你可以输出来看下是什么格式
    
    NSInteger timeSp = [datenow timeIntervalSince1970]*1000;
    
    return timeSp;
}

//获取当前时间字符串
- (NSString *)getCurrentDate
{
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];

       // ----------设置你想要的格式,hh与HH的区别:分别表示12小时制,24小时制

       [formatter setDateFormat:@"MM-dd HH:mm"];

       //现在时间,你可以输出来看下是什么格式

       NSDate *datenow = [NSDate date];

       //----------将nsdate按formatter格式转成nsstring

       NSString *currentTimeString = [formatter stringFromDate:datenow];

       NSLog(@"currentTimeString =  %@",currentTimeString);

       return currentTimeString;
}





#pragma mark - setter and getter

- (UITableView *)tableView
{
    if (!_tableView) {
        _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, cl_kNavigationBarHeight, ScreenWidth, ScreenHeight - cl_kNavigationBarHeight - 45 * WIDTHRADIU) style:UITableViewStyleGrouped];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.showsHorizontalScrollIndicator = NO;
        _tableView.estimatedSectionHeaderHeight = 0.1;
        _tableView.estimatedSectionFooterHeight = 0.1;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.backgroundColor = [UIColor clearColor];
        [_tableView registerNib:[UINib nibWithNibName:@"WithDrawBannerCell" bundle:nil] forCellReuseIdentifier:@"WithDrawBannerCell"];
    }
    return _tableView;
}

- (NSArray *)dataArray
{
    if (!_dataArray) {
//        _dataArray = @[
//            [NSNumber numberWithDouble:1.0],[NSNumber numberWithDouble:3.0],[NSNumber numberWithDouble:5.0],[NSNumber numberWithDouble:10.0],[NSNumber numberWithDouble:20.0],[NSNumber numberWithDouble:50.0]
            _dataArray = @[
                [NSNumber numberWithDouble:1.0],[NSNumber numberWithDouble:3.0],[NSNumber numberWithDouble:10.0]];
    }
    return _dataArray;
}
- (UICollectionView *)collectionView
{
    if (!_collectionView) {
        UICollectionViewFlowLayout *layOut = [[UICollectionViewFlowLayout alloc]init];
        layOut.headerReferenceSize = CGSizeMake(CGRectGetWidth(self.view.bounds), 35 * WIDTHRADIU);
        layOut.minimumInteritemSpacing = 0;
        layOut.minimumLineSpacing = 0;
        _collectionView = [[UICollectionView alloc]initWithFrame:CGRectZero collectionViewLayout:layOut];
        
        _collectionView.backgroundColor = [UIColor colorWithHex:0xf4f4f4];
        _collectionView.showsHorizontalScrollIndicator = NO;
        _collectionView.showsVerticalScrollIndicator = NO;
        _collectionView.delegate = self;
        _collectionView.dataSource = self;
        [_collectionView registerClass:[WithDrawCollectionViewCell class] forCellWithReuseIdentifier:@"cell"];
         [_collectionView registerClass:[CoinsExchangeCollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"headerCell"];
          [_collectionView registerClass:[CoinsFooterView class] forSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:@"footerCell"];
        [_collectionView registerClass:[WithDrawFooterView class] forSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:@"WithDrawFooterView"];
        [_collectionView addSubview:self.headerView];
        
        _collectionView.contentInset = UIEdgeInsetsMake(94* WIDTHRADIU, 0, 0,0);
    }
    return _collectionView;
}
- (WithDrawView *)headerView
{
    if (!_headerView) {
        _headerView = [[WithDrawView alloc]initWithFrame:CGRectMake(0, - 94 * WIDTHRADIU, ScreenWidth, 94 * WIDTHRADIU)];
    }
    return _headerView;
}
- (UIButton *)btn_Withdraw
{
    if (!_btn_Withdraw) {
        _btn_Withdraw =[UIButton buttonWithType:UIButtonTypeCustom];
        _btn_Withdraw.backgroundColor = [UIColor colorWithHex:0xf98505];
        _btn_Withdraw.titleLabel.font = [UIFont systemFontOfSize:15 * WIDTHRADIU];
        [_btn_Withdraw setTitle:@"立即提现" forState:UIControlStateNormal];
        [_btn_Withdraw addTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _btn_Withdraw;
}
/*
#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.
}
*/
#pragma mark - 获取话费充值金额
- (void)getPhoneInfo{
    NSString *url = [NSString stringWithFormat:@"%@qmm/channel/info",[NetworkConfig ipYinShuConfig]];
//    NSString *url = [NSString stringWithFormat:@"%@qmm/channel/info",@"http://172.16.10.18:8017/"];
    NSDictionary *params = @{
                          @"uid":[NSNumber numberWithInteger:[getPeopleID PeopleID]],
                          @"tel":[getPeopleID PeopleIphoneNmber],
                          };
    WeakSelf
    [NetworkRequest PostNo:url Params:params Success:^(id _Nonnull objc) {
        NSLog(@"%@",objc);
        if ([objc isKindOfClass:[NSDictionary class]]) {
            NSString *state = [NSString stringWithFormat:@"%@",objc[@"state"]];
            if ([state isEqualToString:@"200"]) {
                weakSelf.PhoneInfoArr = objc[@"result"];
                [weakSelf.tableView reloadData];
            }
        }
        
    } Failure:^(id _Nonnull error) {
        NSLog(@"%@",error);
    }];
}
@end
