//
//  MyBankDetailController.m
//  Open
//
//  Created by 雷俊博 on 2020/8/10.
//  Copyright © 2020 黄江涛 . All rights reserved.
//

#import "MyBankDetailController.h"
#import "BuyedProductListCell.h"
#import "ProductRechargeController.h"
#import "SaveOrderListController.h"
#import "SaveWithDrawController.h"
#import "HoldingDetailController.h"
#import "ProductDetailModel.h"
#import "SaveSettingController.h"
#import "SaveProductEmptyView.h"
#import "KKAlertView.h"


@interface MyBankDetailController ()<UITableViewDelegate,UITableViewDataSource>
{
    NSMutableDictionary*proOrderDic;
}

@property (nonatomic, strong)UIView*cardView;

@property (nonatomic, strong)UILabel* lb_money;

@property (nonatomic, strong)UIView* headerView;

@property (nonatomic, strong)UITableView* tableView;

@property (nonatomic, strong)UILabel* lb_message;

@property (nonatomic, strong)SaveProductModel* currentModel;

@property (nonatomic, strong)SaveProductEmptyView*emptyView;

@property (nonatomic, strong)UILabel* holdLabel;

@property (nonatomic, strong)UILabel* banklabel;

@end

@implementation MyBankDetailController
- (void)viewDidLayoutSubviews
{
    [super viewDidLayoutSubviews];
}
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    UIBarButtonItem *bar = [[UIBarButtonItem alloc] initWithTitle:@"返回" style:0 target:nil action:nil];
    [self.navigationItem setBackBarButtonItem:bar];
    
    [GTCountSDK trackCountEvent:@"save_wudangAccountInfoCount" withArgs:nil];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor colorWithHex:0xf4f4f4];
    proOrderDic = [NSMutableDictionary dictionary];
    NSData *myEncodedObject  = [[NSUserDefaults standardUserDefaults]objectForKey:@"productInfo"];
     self.currentModel = [NSKeyedUnarchiver unarchiveObjectWithData:myEncodedObject];
    
    [self.view addSubview:self.cardView];
    [self.view addSubview:self.headerView];
    [self.view addSubview:self.tableView];
    //底部message
    [self.view addSubview:self.lb_message];
    
    //if (self.proArr.count == 0) {
        [self.view addSubview:self.emptyView];
   // }
    
    
    
    [self.cardView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.offset(10 * WIDTHRADIU);
        make.top.offset(cl_kNavigationBarHeight + 10 * WIDTHRADIU);
        make.width.offset(ScreenWidth - 20 * WIDTHRADIU);
        make.height.mas_greaterThanOrEqualTo(50 * WIDTHRADIU);
    }];
    [self.headerView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.cardView.mas_bottom).offset(5 * WIDTHRADIU);
        make.left.offset(10 * WIDTHRADIU);
        make.width.offset(ScreenWidth - 20 * WIDTHRADIU);
        make.height.mas_greaterThanOrEqualTo(50 * WIDTHRADIU);
    }];
    
    CGFloat bottomSpace = 0.0;
    if (cl_kNavigationBarHeight > 64) {
        bottomSpace = 20;
    }
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.headerView.mas_bottom).offset(0);
        make.left.offset(10 * WIDTHRADIU);
        make.right.offset(-10 * WIDTHRADIU);
        make.bottom.offset(-20 * WIDTHRADIU - bottomSpace);
    }];
    [self.lb_message mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.tableView.mas_bottom);
        make.left.mas_equalTo(0);
        make.width.mas_equalTo(ScreenWidth);
        make.height.offset(20 * WIDTHRADIU);
    }];
    
   
        [self.emptyView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(self.tableView);
            make.left.offset(0);
            make.width.offset(ScreenWidth);
            make.height.mas_greaterThanOrEqualTo(50 * WIDTHRADIU);
        }];
    
    [self.view layoutIfNeeded];
    
    UIBezierPath *maskPath = [UIBezierPath bezierPathWithRoundedRect:self.headerView.bounds
                                                                 byRoundingCorners:UIRectCornerTopLeft | UIRectCornerTopRight
                                                                       cornerRadii:CGSizeMake(12, 12)];
    CAShapeLayer *maskLayer = [[CAShapeLayer alloc] init];
    maskLayer.frame = self.headerView .bounds;
    maskLayer.path = maskPath.CGPath;
    self.headerView .layer.mask = maskLayer;
    
    if (self.type == SaveFromTypeBiCai) {
        if (self.bcCardModel.subModel.retList.count != 0) {
            self.emptyView.hidden = YES;
        }
        
        [self bcGetHoldInfoRequest:self.bcCardModel];
    }else {
        if (self.proArr.count != 0) {
            self.emptyView.hidden = YES;
        }
        
        [self proInterestRequest];
        //检测产品购买
        [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(refreshBalanceData) name:KKSBGETBalanceNotificationName object:nil];
    }
    
   
}


#pragma mark - 通知绑定方法
- (void)refreshBalanceData
{
    [self getPayAccountInfoRequest];
}

#pragma mark - 获取支付账户信息
- (void)getPayAccountInfoRequest
{
    NSString* url = [NSString stringWithFormat:@"%@%@",[NetworkConfig ipYinShuConfig],YSGETAccountInfoRequest];
    
    SaveAccountSubUserInfoModel*infoModel = self.infoModel.SUBPACKS[0];
    
    NSDictionary*params = @{
        @"accNo": infoModel.CARDNBR
    };
    
    NSLog(@"银数账户查询余额url:%@",url);
    NSLog(@"params:%@",params);
    
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    NSString *strHeader = [NSString stringWithFormat:@"IOS#%@",[[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleShortVersionString"]];
    NSLog(@"strHeader:%@",strHeader);
    [manager.requestSerializer setValue:strHeader forHTTPHeaderField:@"User-Agent"];
       
    [manager POST:url parameters:params headers:nil progress:^(NSProgress * _Nonnull uploadProgress) {
       
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
       [KKLoadingAnimationView dismiss];
       NSLog(@"responseObject:%@",responseObject);
        NSString*state = [NSString stringWithFormat:@"%@",responseObject[@"state"]];
        NSString* result = [NSString stringWithFormat:@"%@",responseObject[@"result"]];
         NSString*describe = [NSString stringWithFormat:@"%@",responseObject[@"describe"]];
        if ([state isEqualToString:@"200"]) {
            NSDictionary*dic = [Tools dencode:result];
            NSLog(@"result:%@",[Tools dencode:result]);
            self.cardModel = [SaveAccountCardInfo mj_objectWithKeyValues:dic];
            [self refreshPayViewData];
        }else{
           NSDictionary*dic = [Tools dictionaryWithJsonString:describe];
            NSLog(@"describe:%@",dic);
           NSString*code = nil;
           NSString*message = nil;
           if (![Tools isBlankString:[NSString stringWithFormat:@"%@",dic[@"code"]]]) {
               code = [NSString stringWithFormat:@"%@",dic[@"code"]];
           }else if (![Tools isBlankString:[NSString stringWithFormat:@"%@",dic[@"RETCODE"]]]){
               code = [NSString stringWithFormat:@"%@",dic[@"RETCODE"]];
           }
           
           if (code) {
               message = [KBankErrorCode showErrorMessageWithErrorCode:code];
               
               if (message) {
                   [SVProgressHUD showErrorWithStatus:message];
               }else{
                   [SVProgressHUD showErrorWithStatus:@"系统错误"];
               }
           }else{
               [SVProgressHUD showErrorWithStatus:@"系统错误"];
           }
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {

       NSLog(@"error:%@",error);
        [SVProgressHUD showInfoWithStatus:@"网络异常"];
    }];
}



#pragma mark - 刷新数据
- (void)refreshPayViewData
{
    self.lb_money.text = [NSString stringWithFormat:@"%.2f",self.cardModel.AVAIL_BAL.doubleValue];;
}



#pragma mark - 产品购买赎回查询
- (void)proInterestRequest
{
    [KKLoadingAnimationView show];
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        NSLog(@"开始");
        dispatch_semaphore_t sema = dispatch_semaphore_create(0);
         for (int i = 0; i < self.proArr.count; i++) {
               YSBuyedProModel*model = self.proArr[i];
               
               NSString* url = [NSString stringWithFormat:@"%@%@",[NetworkConfig ipYinShuConfig],YSProBuyOrRedeemQuery];
//               SaveAccountSubUserInfoModel*infoModel = self.infoModel.SUBPACKS[0];
               NSDictionary*params = @{
                   @"acctNo":[Tools isBlankString:model.accountNo]?@"" :model.accountNo,
                   @"order": model.Id ? model.Id :@""
               };
               
               NSLog(@"产品 购买 赎回 查询url:%@",url);
               NSLog(@"params:%@",params);
               AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
               NSString *strHeader = [NSString stringWithFormat:@"IOS#%@",[[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleShortVersionString"]];
               NSLog(@"strHeader:%@",strHeader);
               [manager.requestSerializer setValue:strHeader forHTTPHeaderField:@"User-Agent"];
                  
               [manager POST:url parameters:params headers:nil progress:^(NSProgress * _Nonnull uploadProgress) {
                  
               } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                  //[KKLoadingAnimationView dismiss];
                  NSLog(@"responseObject:%@",responseObject);
                   NSString*state = [NSString stringWithFormat:@"%@",responseObject[@"state"]];
                   NSString* result = responseObject[@"result"];
                   if ([state isEqualToString:@"200"]) {
                       NSDictionary*dic = [Tools dencode:result];
                       ProductDetailModel*detailModel = [ProductDetailModel mj_objectWithKeyValues:dic];
                       NSLog(@"dic:%@",dic);
                       //[self->proOrderDic setValue:dic[@"CURR_INT"] forKey:model.Id];
                       [self->proOrderDic setObject:detailModel forKey:model.Id];
                      
                   }
                    dispatch_semaphore_signal(sema);
                   
               } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                  //[KKLoadingAnimationView dismiss];
                    dispatch_semaphore_signal(sema);
                  NSLog(@"error:%@",error);
               }];
             dispatch_semaphore_wait(sema, DISPATCH_TIME_FOREVER);
           }
        NSLog(@"结束");
        dispatch_async(dispatch_get_main_queue(), ^{
            [KKLoadingAnimationView dismiss];
            [self.tableView reloadData];
        });
    });
    
   
    
    
    
    
}


#pragma mark - 比财 资产持仓产品
- (void)bcGetHoldInfoRequest:(BCOPenedCardModel *)kmodel {
    
    NSString* url = [NSString stringWithFormat:@"%@%@",[NetworkConfig ipYinShuConfig],BCGetHoldProListRequest];
    NSLog(@"比财资产持仓产品url:%@",url);
    NSMutableDictionary *params = [NetworkPublicParams getBCPublicParams];
    
    [params setObject:[getPeopleID PeopleIphoneNmber] forKey:@"loginPhoneNum"];
    [params setObject:kmodel.orgId forKey:@"orgId"];
    [params setObject:@(1)forKey:@"currentPage"];
    [params setObject:@"4" forKey:@"prdType"];
    [params setObject:@"4" forKey:@"depositTypeId"];
    [params setObject:@(0)forKey:@"reqType"];
    
    
    NSLog(@"params:%@",params);
    
    [KKLoadingAnimationView show];
    [NetworkRequest Post6:url Params:params Success:^(id _Nonnull objc) {
        [KKLoadingAnimationView dismiss];
        NSLog(@"objc:%@",objc);
        NSString *state = [NSString stringWithFormat:@"%@",objc[@"state"]];
        NSString *describe = [NSString stringWithFormat:@"%@",objc[@"describe"]];
        if ([state isEqualToString:@"200"]) {
           
            BCHoldProListModel* model = [BCHoldProListModel mj_objectWithKeyValues:objc[@"result"]];

            kmodel.subModel = model;
            [self refreshUIData];
            
        }else {
            [self alertShow:describe];
        }
    } Failure:^(NSError* error) {
        [KKLoadingAnimationView dismiss];
        NSLog(@"error:%@",error);
        [self alertShow:@"网络出小差了,请稍后重试"];
        
    }];
    
}

- (void)refreshUIData {
    self.holdLabel.text = [NSString stringWithFormat:@"%@",self.bcCardModel.subModel.totalHoldAmount];
    if (self.bcCardModel.subModel.retList.count != 0) {
        self.emptyView.hidden = YES;
    }
    [self.tableView reloadData];
}


#pragma mark - 利息试算
- (void)bcCalcRedmptionRequest:(BCHoldProRetListModel *)listModel {
    
    NSString* url = [NSString stringWithFormat:@"%@%@",[NetworkConfig ipYinShuConfig],BCCalcRedemptionRequest];
    NSLog(@"比财利息试算url:%@",url);
    NSMutableDictionary *params = [NetworkPublicParams getBCPublicParams];
    
    [params setObject:[getPeopleID PeopleIphoneNmber] forKey:@"loginPhoneNum"];
    [params setObject:self.bcCardModel.orgId forKey:@"orgId"];
    [params setObject:listModel.dynamicList.amount.fieldValue forKey:@"amount"];
    [params setObject:listModel.prdIndexId forKey:@"prdIndexId"];
    [params setObject:listModel.reqSerial forKey:@"reqSerial"];
    
    
    NSLog(@"params:%@",params);
    
    [NetworkRequest Post6:url Params:params Success:^(id _Nonnull objc) {
        NSLog(@"objc:%@",objc);
        NSString *state = [NSString stringWithFormat:@"%@",objc[@"state"]];
//        NSString *describe = [NSString stringWithFormat:@"%@",objc[@"describe"]];
        if ([state isEqualToString:@"200"]) {
           
            listModel.profit = objc[@"result"][@"profit"];
            [self.tableView reloadData];
            
        }
    } Failure:^(NSError* error) {
        NSLog(@"error:%@",error);
        
        
    }];
    
}



#pragma mark - 比财 充值校验
- (void)checkBCRechargeRequest{
    NSString* url = [NSString stringWithFormat:@"%@%@",[NetworkConfig ipYinShuConfig],BCCheckRechargeRequest];
    NSMutableDictionary *params = [NetworkPublicParams getBCPublicParams];
    [params setObject:[getPeopleID PeopleIphoneNmber] forKey:@"loginPhoneNum"];
    [params setObject:self.bcCardModel.orgId forKey:@"orgId"];
    
    NSLog(@"比财充值校验url:%@",url);
    NSLog(@"params:%@",params);
    
    [KKLoadingAnimationView show];
    [NetworkRequest Post6:url Params:params Success:^(id _Nonnull objc) {
        
        NSLog(@"objc:%@",objc);
        NSString *state = [NSString stringWithFormat:@"%@",objc[@"state"]];
        NSString *describe = [NSString stringWithFormat:@"%@",objc[@"describe"]];
        if ([state isEqualToString:@"200"]) {
            
            [self bcGetEleAccountInfoRequest:@"充值" model:nil];
            return;
            
        }else{
            
            NSString* code = [NSString stringWithFormat:@"%@",objc[@"result"][@"code"]];
            if ([code isEqualToString:@"Y00010"]) {
                [self doNotSupportChargeAlerShow:[NSString stringWithFormat:@"%@暂不支持在线充值，请使用绑定的银行卡进行转账",self.bcCardModel.bankName]];
            }else{
                [self alertShow:describe];
            }
            
           
        }
        [KKLoadingAnimationView dismiss];
    } Failure:^(NSError* error) {
        [KKLoadingAnimationView dismiss];
        
        NSLog(@"error:%@",error);
        [self alertShow:@"网络出小差了,请稍后重试"];
        
    }];
}

#pragma mark - 不支持在线充值提示
- (void)doNotSupportChargeAlerShow:(NSString*)message {
    [KKAlertView showAlertViewWithVC:self message:message block:^(KKAlertViewType type) {
        if (type == KKAlertViewTypeDetailText) {
            
            [KKLoadingAnimationView show];
            [self bcGetEleAccountInfoRequest:@"转账攻略" model:nil];
        }else if (type == KKAlertViewTypeCopy) {
            if (self.bcCardModel.bankUserCode) {
                UIPasteboard *pab = [UIPasteboard generalPasteboard];
                pab.string = self.bcCardModel.bankUserCode;
                if (pab == nil) {
                    [Tools showMessage:@"复制失败"];
                } else {
                    [Tools showMessage:@"已复制"];
                }
            }else{
                [Tools showMessage:@"复制失败"];
            }
            
        }

    }];
}

#pragma mark - 比财 提现校验
- (void)checkBCWithDrawalRequest {
    NSString* url = [NSString stringWithFormat:@"%@%@",[NetworkConfig ipYinShuConfig],BCCheckWithDrawalRequest];
    NSMutableDictionary *params = [NetworkPublicParams getBCPublicParams];
    [params setObject:[getPeopleID PeopleIphoneNmber] forKey:@"loginPhoneNum"];
    [params setObject:self.bcCardModel.orgId forKey:@"orgId"];
    
    NSLog(@"比财提现校验url:%@",url);
    NSLog(@"params:%@",params);
    
    [KKLoadingAnimationView show];
    [NetworkRequest Post6:url Params:params Success:^(id _Nonnull objc) {
        
        NSLog(@"objc:%@",objc);
        NSString *state = [NSString stringWithFormat:@"%@",objc[@"state"]];
        NSString *describe = [NSString stringWithFormat:@"%@",objc[@"describe"]];
        if ([state isEqualToString:@"200"]) {
          
            
            
            [self bcGetEleAccountInfoRequest:@"提现" model:nil];
            return;
            
        }else{
            [self alertShow:describe];
        }
        [KKLoadingAnimationView dismiss];
    } Failure:^(NSError* error) {
        [KKLoadingAnimationView dismiss];
        
        NSLog(@"error:%@",error);
        [self alertShow:@"网络出小差了,请稍后重试"];
        
    }];
}

//#pragma mark - 比财产品详情
//- (void)getBiCaiDetailInfoRequest {
//    NSString* url = [NSString stringWithFormat:@"%@%@",[NetworkConfig ipYinShuConfig],BCGetProductInfoRequest];
//    NSLog(@"比财产品详情url:%@",url);
//    NSMutableDictionary *params = [NetworkPublicParams getBCPublicParams];
//
//    [params setObject:[getPeopleID PeopleIphoneNmber] forKey:@"loginPhoneNum"];
//    [params setObject:[NSString stringWithFormat:@"%ld",model.prdId] forKey:@"productId"];
//
//
//    NSLog(@"params:%@",params);
//
//    [KKLoadingAnimationView show];
//    [NetworkRequest Post6:url Params:params Success:^(id _Nonnull objc) {
//        [KKLoadingAnimationView dismiss];
//        NSLog(@"objc:%@",objc);
//        NSString *state = [NSString stringWithFormat:@"%@",objc[@"state"]];
//        NSString *describe = [NSString stringWithFormat:@"%@",objc[@"describe"]];
//        if ([state isEqualToString:@"200"]) {
//            SaveBCProductInfoModel* infoModel = [SaveBCProductInfoModel mj_objectWithKeyValues:objc[@"result"]];
//
//
//
//        }else{
//            [Tools showMessage:describe];
//        }
//
//        [self.tableView reloadData];
//    } Failure:^(NSError* error) {
//        [KKLoadingAnimationView dismiss];
//        NSLog(@"error:%@",error);
//
//        [Tools showMessage:@"网络出小差了,请稍后重试"];
//
//    }];
//}


#pragma mark - 比财 电子账户信息详情
- (void)bcGetEleAccountInfoRequest:(NSString *)type model:(id)retModel {
    
    NSString* url = [NSString stringWithFormat:@"%@%@",[NetworkConfig ipYinShuConfig],BCGETAccountInfoRequest];
    NSLog(@"比财电子账户详情url:%@",url);
    NSMutableDictionary *params = [NetworkPublicParams getBCPublicParams];
    
    [params setObject:[getPeopleID PeopleIphoneNmber] forKey:@"loginPhoneNum"];
    [params setObject:self.bcCardModel.orgId forKey:@"orgId"];
    
    
    NSLog(@"params:%@",params);
    
    [NetworkRequest Post6:url Params:params Success:^(id _Nonnull objc) {
        [KKLoadingAnimationView dismiss];
        NSLog(@"objc:%@",objc);
        NSString *state = [NSString stringWithFormat:@"%@",objc[@"state"]];
        NSString *describe = [NSString stringWithFormat:@"%@",objc[@"describe"]];
        if ([state isEqualToString:@"200"]) {
           
            BCAccountInfoModel* model = [BCAccountInfoModel mj_objectWithKeyValues:objc[@"result"]];
            
            if ([type isEqualToString:@"充值"]) {
                ProductRechargeController*vc = [ProductRechargeController new];
                vc.title = @"充值";
                vc.bcInfoModel = model;
                vc.type = self.type;
                vc.hidesBottomBarWhenPushed = YES;
                [self.navigationController pushViewController:vc animated:YES];
            }else if ([type isEqualToString:@"提现"]) {
                SaveWithDrawController*vc = [SaveWithDrawController new];
                vc.title = @"提现";
                vc.type = self.type;
                vc.bcAccountInfoModel = model;
                [self.navigationController pushViewController:vc animated:YES];
            }else if ([type isEqualToString:@"已购产品"]) {
                HoldingDetailController* detailVC = [HoldingDetailController new];
                detailVC.title = @"持有详情";
                detailVC.type = self.type;
                detailVC.bcholdProRetModel = (BCHoldProRetListModel *)retModel;
                detailVC.bcAccountInfoModel = model;
                [self.navigationController pushViewController:detailVC animated:YES];
            }else if ([type isEqualToString:@"更多"]){
                SaveSettingController*vc = [SaveSettingController new];
                vc.title = @"更多服务";
                vc.bcAccountModel = model;
                vc.type = SaveFromTypeBiCai;
                [self.navigationController pushViewController:vc animated:YES];
            }else if ([type isEqualToString:@"转账攻略"]){
                
                WebVC * vc = [WebVC new];
                vc.title= @"转账攻略";
                vc.url = @"http://nginx.weface.com.cn/appH5/transMoney/index.html";
                vc.hidesBottomBarWhenPushed = YES;
                vc.infoModel = model;
                [self.navigationController pushViewController:vc animated:YES];
            //http://172.16.10.136/projects/html-nginx/html-nginx/appH5/transMoney/index.html
            }
            
            
        } else{
            [self alertShow:describe];
        }
        
    } Failure:^(NSError* error) {
        [KKLoadingAnimationView dismiss];
        NSLog(@"error:%@",error);
        
        [self alertShow:@"网络出小差了,请稍后重试"];
        
    }];
    
}



#pragma mark - 提示
- (void)alertShow:(NSString *)msg
{
    if (@available(iOS 9.0,*)) {
        
        UIAlertController * alertV = [UIAlertController alertControllerWithTitle:@"提示" message:msg preferredStyle:UIAlertControllerStyleAlert];
        
        UIAlertAction *confirm = [UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            
        }];
        
        [alertV addAction:confirm];
        
        [self presentViewController:alertV animated:YES completion:nil];
        
    }else{
        UIAlertView *alertV = [[UIAlertView alloc]initWithTitle:@"提示" message:msg delegate:self cancelButtonTitle:@"确定" otherButtonTitles: nil];
        [alertV show];
    }
}


#pragma mark - UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    if (self.type == SaveFromTypeBiCai) {
        return self.bcCardModel.subModel.retList.count;
    }
    
    return self.proArr.count;
}

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


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (self.type == SaveFromTypeBiCai) {
        BCHoldProRetListModel* holdModel = self.bcCardModel.subModel.retList[indexPath.section];
        BuyedProductListCell*cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
        cell.lb_bankName.text = [NSString stringWithFormat:@"%@|%@",holdModel.orgName,holdModel.prdName];
        cell.lb_amount.text = [NSString stringWithFormat:@"+%@",holdModel.dynamicList.amount.fieldValue];
        
        if (holdModel.profit) {
            cell.lb_sy.text = holdModel.profit;
        }else{
            cell.lb_sy.text = @"--";
            
            [self bcCalcRedmptionRequest:holdModel];
        }
       
        
        return cell;
    }
    YSBuyedProModel*model = self.proArr[indexPath.section];
    BuyedProductListCell*cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    NSString*note = nil;
    if ([model.product isEqualToString:@"35"]) {
        note = @"黔宝源";
    }else if ([model.product isEqualToString:@"36"]){
        note = @"黔宝聚";
    }else{
        note = @"--";
    }
    cell.lb_bankName.text = [NSString stringWithFormat:@"乌当农商银行|%@",note];
    cell.lb_amount.text = [NSString stringWithFormat:@"+%.2f",model.account.doubleValue/100.0];
    ProductDetailModel* detailModel = proOrderDic[model.Id];
    NSString* num = nil;
    if (detailModel == nil) {
        num = @"--";
    }else{
        num = [NSString stringWithFormat:@"%.2f",detailModel.CURR_INT.doubleValue];
    }
    cell.lb_sy.text = num;
    
    
    return cell;
}

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

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

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    UIBarButtonItem *bar = [[UIBarButtonItem alloc] initWithTitle:@"返回" style:0 target:nil action:nil];
    [self.navigationItem setBackBarButtonItem:bar];
    
    if (self.type == SaveFromTypeBiCai) {
        BCHoldProRetListModel* holdModel = self.bcCardModel.subModel.retList[indexPath.section];
        [KKLoadingAnimationView show];
        [self bcGetEleAccountInfoRequest:@"已购产品" model:holdModel];
    }else {
        YSBuyedProModel*model = self.proArr[indexPath.section];
        ProductDetailModel* detailModel = proOrderDic[model.Id];
        if (detailModel) {
            for (SaveSubProductModel*kModel in self.currentModel.SUBPACKS) {
                if ([kModel.RET_PRD_CODE isEqualToString:model.product]) {
                    HoldingDetailController* detailVC = [HoldingDetailController new];
                    detailVC.title = @"持有详情";
                    detailVC.model = model;
                    detailVC.detailModel = detailModel;
                    detailVC.cardModel = self.cardModel;
                    detailVC.infoModel = self.infoModel;
                    detailVC.subModel = kModel;
                    [self.navigationController pushViewController:detailVC animated:YES];
                    break;
                }
            }
            
        }
    }
  
   
}


#pragma mark - event response
- (void)txBtnClick:(UIButton *)sender
{
    if (self.type == SaveFromTypeBiCai) {
        
        [self checkBCWithDrawalRequest];
        
    }else{
        SaveWithDrawController*vc = [SaveWithDrawController new];
        vc.title = @"提现";
        vc.infoModel = self.infoModel;
        vc.cardModel = self.cardModel;
        [self.navigationController pushViewController:vc animated:YES];
    }
    
    
}

- (void)czBtnClick:(UIButton *)sender
{
    if (self.type == SaveFromTypeBiCai) {
        [self checkBCRechargeRequest];
    }else{
        ProductRechargeController*vc = [ProductRechargeController new];
        vc.title = @"充值";
       vc.hidesBottomBarWhenPushed = YES;
       vc.infoModel = self.infoModel;
       vc.cardModel = self.cardModel;
       [self.navigationController pushViewController:vc animated:YES];
    }
    
    
}

- (void)detailBtnClick:(UIButton *)sender
{
    if (self.type == SaveFromTypeBiCai) {
        SaveOrderListController* vc = [SaveOrderListController new];
        vc.title = @"交易记录";
        vc.type = self.type;
        vc.bcCardModel = self.bcCardModel;
        [self.navigationController pushViewController:vc animated:YES];
    }else{
        SaveOrderListController* vc = [SaveOrderListController new];
        vc.title = @"交易记录";
        vc.cardModel = self.cardModel;
        [self.navigationController pushViewController:vc animated:YES];
    }
    
    
}

- (void)setBtnClick:(UIButton *)sender
{
    if (self.type == SaveFromTypeBiCai) {
        [KKLoadingAnimationView show];
        [self bcGetEleAccountInfoRequest:@"更多" model:nil];
    }else{
        SaveSettingController*vc = [SaveSettingController new];
        vc.title = @"更多服务";
        vc.infoModel = self.infoModel;
        [self.navigationController pushViewController:vc animated:YES];
    }
    
}

- (void)checkBtnClick:(UIButton *)sender {
    
    sender.selected = !sender.selected;
    
    NSString * bankNum = nil;
    
    if (self.type == SaveFromTypeBiCai) {
        if (sender.selected) {
            bankNum = [self jointWithString:self.bcCardModel.bankUserCode];
        }else{
            bankNum = [NSString stringWithFormat:@"%@ **** **** ****  %@",[self.bcCardModel.bankUserCode substringToIndex:4],[self.bcCardModel.bankUserCode substringFromIndex:self.bcCardModel.bankUserCode.length - 4]];
        }
        
    
    }else{
        if (sender.selected) {
            bankNum = [self jointWithString:self.cardModel.CARDNBR];
        }else{
            bankNum = [NSString stringWithFormat:@"%@ **** **** ****  %@",[self.cardModel.CARDNBR substringToIndex:4],[self.cardModel.CARDNBR substringFromIndex:self.cardModel.CARDNBR.length - 4]];
        }
        
    }
    
    
    self.banklabel.text = bankNum;
   
}

- (void)copyBtnClick:(UIButton *)sender {
    
    NSString * bankNum = nil;
    
    if (self.type == SaveFromTypeBiCai) {
        
        bankNum = self.bcCardModel.bankUserCode;
        
    }else{
        
        bankNum = self.cardModel.CARDNBR;
    }
    
    UIPasteboard *pab = [UIPasteboard generalPasteboard];
    pab.string = bankNum;
    if (pab == nil) {
        [Tools showMessage:@"复制失败"];
    } else {
        [Tools showMessage:@"已复制"];
    }
    
}


#pragma mark - public methods
-(id)getXiblWithClassName:(NSString *)className
{
    return [[NSBundle mainBundle]loadNibNamed:className owner:self options:nil].lastObject;
}


#pragma mark - 拼接成中间有空格的字符串
- (NSString *)jointWithString:(NSString *)str
{
    NSString *getString = @"";
    
    int a = (int)str.length/4;
    int b = (int)str.length%4;
    int c = a;
    if (b>0)
    {
        c = a+1;
    }
    else
    {
        c = a;
    }
    for (int i = 0 ; i<c; i++)
    {
        NSString *string = @"";
        
        if (i == (c-1))
        {
            if (b>0)
            {
                string = [str substringWithRange:NSMakeRange(4*(c-1), b)];
            }
            else
            {
                string = [str substringWithRange:NSMakeRange(4*i, 4)];
            }
            
        }
        else
        {
            string = [str substringWithRange:NSMakeRange(4*i, 4)];
        }
        getString = [NSString stringWithFormat:@"%@ %@",getString,string];
    }
    return getString;
}

#pragma mark - getters
- (UIView *)cardView
{
    if (!_cardView) {
        _cardView = [[UIView alloc]init];
        _cardView.backgroundColor = [UIColor colorWithHex:0x137ef6];
        _cardView.layer.cornerRadius = 12 * WIDTHRADIU;
        
        //银行名称
        UILabel* lb_bankName = [[UILabel alloc]init];
        lb_bankName.textColor = [UIColor whiteColor];
        lb_bankName.font = [UIFont boldSystemFontOfSize:18* WIDTHRADIU];
        [_cardView addSubview:lb_bankName];
        [lb_bankName mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.offset(20 * WIDTHRADIU);
            make.left.offset(15 * WIDTHRADIU);
        }];
        
        //银行卡号
        UILabel* lb_bankNo = [[UILabel alloc]init];
        //lb_bankNo.text = @"6217 **** **** **** 0031";
        lb_bankNo.textColor = [UIColor whiteColor];
        lb_bankNo.font = [UIFont boldSystemFontOfSize:18* WIDTHRADIU];
        [_cardView addSubview:lb_bankNo];
        [lb_bankNo mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(lb_bankName.mas_bottom).offset(10 * WIDTHRADIU);
            make.left.equalTo(lb_bankName);
        }];
        
        self.banklabel = lb_bankNo;
        
        
        //设置按钮
        UIButton*setBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [setBtn setImage:[UIImage imageNamed:@"shezhi"] forState:UIControlStateNormal];
        [setBtn addTarget:self action:@selector(setBtnClick:) forControlEvents:UIControlEventTouchUpInside];
        [_cardView addSubview:setBtn];
        [setBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.offset(10 * WIDTHRADIU);
            make.right.offset(0 * WIDTHRADIU);
            make.width.offset(60 * WIDTHRADIU);
            make.height.offset(40 * WIDTHRADIU);
        }];
        
        
        
        UIButton* checkBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        
        [checkBtn setImage:[UIImage imageNamed:@"hiddeneye"] forState:UIControlStateNormal];
        [checkBtn setImage:[UIImage imageNamed:@"eye_show"] forState:UIControlStateSelected];
        [checkBtn addTarget:self action:@selector(checkBtnClick:) forControlEvents:UIControlEventTouchUpInside];
        [_cardView addSubview:checkBtn];
        [checkBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerY.equalTo(setBtn);
            make.right.equalTo(setBtn.mas_left).offset(10 * WIDTHRADIU);
            make.width.offset(60 * WIDTHRADIU);
            make.height.offset(40 * WIDTHRADIU);
        }];
        
        
        UIButton* copyBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [copyBtn setTitle:@"复制" forState:UIControlStateNormal];
        [copyBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        copyBtn.titleLabel.font = [UIFont systemFontOfSize:15];
        [copyBtn addTarget:self action:@selector(copyBtnClick:) forControlEvents:UIControlEventTouchUpInside];
        [_cardView addSubview:copyBtn];
        [copyBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerY.equalTo(lb_bankNo);
            make.right.equalTo(setBtn);
            make.width.offset(60);
            make.height.offset(40);
        }];
        
        
        //线
        UIView* line = [[UIView alloc]init];
        line.backgroundColor = [UIColor whiteColor];
        [_cardView addSubview:line];
        [line mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.offset(10 * WIDTHRADIU);
            make.right.offset(-10 * WIDTHRADIU);
            make.top.equalTo(lb_bankNo.mas_bottom).offset(15 * WIDTHRADIU);
            make.height.offset(0.5);
        }];
        
        
        //账户余额
        UILabel* lb_rest = [UILabel new];
        lb_rest.text = @"账户余额";
        lb_rest.textColor = [UIColor whiteColor];
        lb_rest.font = [UIFont systemFontOfSize:13* WIDTHRADIU];
        [_cardView addSubview:lb_rest];
        [lb_rest mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(line.mas_bottom).offset(10 * WIDTHRADIU);
            make.left.equalTo(line);
        }];
        
        UILabel* lb_money = [UILabel new];
        lb_money.textColor = [UIColor whiteColor];
        lb_money.font = [UIFont systemFontOfSize:15* WIDTHRADIU];
        [_cardView addSubview:lb_money];
        self.lb_money = lb_money;
        [lb_money mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(lb_rest.mas_bottom).offset(10 * WIDTHRADIU);
            make.left.equalTo(line);
        }];
        
        //提现按钮
        UIButton* txBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [txBtn setTitle:@"提现" forState:UIControlStateNormal];
        [txBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        txBtn.titleLabel.font = [UIFont systemFontOfSize:15 * WIDTHRADIU];
        txBtn.layer.cornerRadius = 6;
        txBtn.layer.borderColor = [UIColor whiteColor].CGColor;
        txBtn.layer.borderWidth = 1;
        [txBtn addTarget:self action:@selector(txBtnClick:) forControlEvents:UIControlEventTouchUpInside];
        [_cardView addSubview:txBtn];
        [txBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(line.mas_bottom).offset(20 * WIDTHRADIU);
            make.right.offset(-10 * WIDTHRADIU);
            make.width.offset(60 * WIDTHRADIU);
            make.height.offset(30 * WIDTHRADIU);
        }];
        //充值按钮
        UIButton* czBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [czBtn setTitle:@"充值" forState:UIControlStateNormal];
        [czBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        czBtn.titleLabel.font = [UIFont systemFontOfSize:15 * WIDTHRADIU];
        czBtn.layer.cornerRadius = 6;
        czBtn.layer.borderColor = [UIColor whiteColor].CGColor;
        czBtn.layer.borderWidth = 1;
        [czBtn addTarget:self action:@selector(czBtnClick:) forControlEvents:UIControlEventTouchUpInside];
        [_cardView addSubview:czBtn];
        [czBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(line.mas_bottom).offset(20 * WIDTHRADIU);
            make.right.equalTo(txBtn.mas_left).offset(-10 * WIDTHRADIU);
            make.width.offset(60 * WIDTHRADIU);
            make.height.offset(30 * WIDTHRADIU);
            make.bottom.offset(-20 * WIDTHRADIU);
        }];
        
        if (self.type == SaveFromTypeBiCai) {
            lb_bankName.text = self.bcCardModel.bankName;
            lb_bankNo.text = [NSString stringWithFormat:@"%@ **** **** ****  %@",[self.bcCardModel.bankUserCode substringToIndex:4],[self.bcCardModel.bankUserCode substringFromIndex:self.bcCardModel.bankUserCode.length - 4]];
            lb_money.text = [NSString stringWithFormat:@"%@",self.bcCardModel.balance];;
        }else{
            lb_bankName.text = @"乌当农商银行";
            lb_bankNo.text = [NSString stringWithFormat:@"%@ **** **** ****  %@",[self.cardModel.CARDNBR substringToIndex:4],[self.cardModel.CARDNBR substringFromIndex:self.cardModel.CARDNBR.length - 4]];
            lb_money.text = [NSString stringWithFormat:@"%.2f",self.cardModel.AVAIL_BAL.doubleValue];;
        }
        
        
        
    }
    return _cardView;
}


- (UIView *)headerView
{
    if (!_headerView) {
        _headerView = [[UIView alloc]init];
        _headerView.backgroundColor = [UIColor colorWithHex:0x137ef6];
        
        //已购产品
        UILabel* lb_buyed = [[UILabel alloc]init];
        lb_buyed.text = @"已购产品(元)";
        lb_buyed.textColor = [UIColor whiteColor];
        lb_buyed.font = [UIFont systemFontOfSize:15 * WIDTHRADIU];
        [_headerView addSubview:lb_buyed];
        [lb_buyed mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.offset(10 * WIDTHRADIU);
            make.left.offset(15 * WIDTHRADIU);
        }];
        
        //银行卡号
        UILabel* lb_money = [[UILabel alloc]init];
        lb_money.textColor = [UIColor whiteColor];
        lb_money.font = [UIFont systemFontOfSize:15 * WIDTHRADIU];
        [_headerView addSubview:lb_money];
        [lb_money mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(lb_buyed.mas_bottom).offset(10 * WIDTHRADIU);
            make.left.equalTo(lb_buyed);
            make.bottom.offset(-10* WIDTHRADIU);
        }];
        self.holdLabel = lb_money;
        
        
        //设置按钮
        UIButton*detailBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [detailBtn setTitle:@"交易明细" forState:UIControlStateNormal];
        [detailBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        detailBtn.titleLabel.font = [UIFont systemFontOfSize:15 * WIDTHRADIU];
        [detailBtn addTarget:self action:@selector(detailBtnClick:) forControlEvents:UIControlEventTouchUpInside];
        [_headerView addSubview:detailBtn];
        [detailBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.offset(0);
            make.right.offset(0 * WIDTHRADIU);
            make.width.offset(80 * WIDTHRADIU);
            //make.height.offset(50 * WIDTHRADIU);
            make.bottom.mas_greaterThanOrEqualTo(0);
        }];
        
        if (self.type == SaveFromTypeBiCai) {
            lb_money.text = [NSString stringWithFormat:@"%@",self.bcCardModel.subModel.totalHoldAmount];
        }else{
            lb_money.text = [NSString stringWithFormat:@"%.2f",self.proSum];
        }
        
        
    }
    return _headerView;
}
- (UITableView *)tableView
{
    if (!_tableView) {
        _tableView = [[UITableView alloc]initWithFrame:CGRectZero style:UITableViewStyleGrouped];
        _tableView.delegate =self;
        _tableView.dataSource = self;
        _tableView.rowHeight = UITableViewAutomaticDimension;
        _tableView.estimatedRowHeight = 30;
        _tableView.estimatedSectionHeaderHeight = 10.0;
        _tableView.estimatedSectionFooterHeight = 10.0;
        [_tableView registerNib:[UINib nibWithNibName:@"BuyedProductListCell" bundle:nil] forCellReuseIdentifier:@"cell"];
        _tableView.bounces = NO;
        _tableView.separatorStyle =  UITableViewCellSeparatorStyleNone;
        _tableView.backgroundColor = [UIColor colorWithHex:0xf4f4f4];
    }
    return _tableView;
}

- (UILabel *)lb_message
{
    if (!_lb_message) {
        _lb_message = [UILabel new];
        _lb_message.textColor = [UIColor colorWithHex:0x4d4d4d];
        _lb_message.font = [UIFont systemFontOfSize:12];
        _lb_message.textAlignment = NSTextAlignmentCenter;
        
        if(self.type == SaveFromTypeBiCai) {
            _lb_message.text = [NSString stringWithFormat:@"本产品服务由%@提供",self.bcCardModel.bankName];
        }else{
            _lb_message.text = @"本产品服务由贵州乌当农商银行提供";
        }
    }
    return _lb_message;
}

- (SaveProductEmptyView *)emptyView
{
    if (!_emptyView) {
        _emptyView = [self getXiblWithClassName:@"SaveProductEmptyView"];
       // _emptyView.frame = CGRectMake(0, 0, ScreenWidth, 141);
        _emptyView.backgroundColor = [UIColor clearColor];
    }
    return _emptyView;
}

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter]removeObserver:self name:KKSBGETBalanceNotificationName object:nil];
}

/*
#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
