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

#import "MyAssetsController.h"

#import "OPenBankListCell.h"
#import "MyAssetsTopView.h"
#import "MyBankDetailController.h"

#import "SaveAccountInfoModel.h"
#import "SaveAccountCardInfo.h"
#import "YSBuyedProModel.h"
#import "ElectAccountOPenSuccessController.h"
#import "OPenAccountController.h"
#import "SaveWelfareAlertView.h"

#import "AiDaAlertView.h"
#import "BCOPenedCardModel.h"
#import "BCHoldProListModel.h"

#import "UIImageView+WebCache.h"

@interface MyAssetsController ()<UITableViewDelegate,UITableViewDataSource>
{
    BOOL WDAccountOPened;
    CGFloat ygSum;
    

    dispatch_group_t group;
}

@property (nonatomic, strong)UITableView* tableView;

@property (nonatomic, strong)MyAssetsTopView* headerView;

@property (nonatomic, strong)UIView* bottomView;

@property (nonatomic, strong)SaveAccountInfoModel* infoModel;

@property (nonatomic, strong)SaveAccountCardInfo* cardModel;

@property (nonatomic, strong)NSArray*proArr;



@property (nonatomic, strong)NSArray*bcCardArray;

@property (nonatomic, copy)NSString* bcSumAmount;



@end

@implementation MyAssetsController
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self.navigationController.navigationBar navBarBackGroundColor:[UIColor colorWithHex:0x137ef6] image:nil isOpaque:YES];//颜色
       
    [self.navigationController.navigationBar navBarBottomLineHidden:YES];
    
    [self queryAccountStateRequest];
    [self bcGetAllOpenedAccountOrgs];
    [self checkISDisplayBottomBannerRequest];
    [self bcQuerySumAmountRequest];
    UIBarButtonItem *bar = [[UIBarButtonItem alloc] initWithTitle:@"返回" style:0 target:nil action:nil];
    [self.navigationItem setBackBarButtonItem:bar];
    
    [GTCountSDK trackCountEvent:@"save_myAssetsCount" withArgs:@{}];//个推统计
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    //init
    group =  dispatch_group_create();
    
    [self configNav];
    
    [self.view addSubview:self.tableView];
    [self.view addSubview:self.bottomView];
    
    //检测产品购买
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(refreshBalanceData) name:KKSBGETBalanceNotificationName object:nil];
}

- (void)configNav
{
    UIButton* backBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [backBtn setTitle:@"返回" forState:UIControlStateNormal];
    [backBtn setImage:[UIImage imageNamed:@"返回"] forState:UIControlStateNormal];
    [backBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    backBtn.frame = CGRectMake(0, 0, 60, 44);
    [backBtn layoutButtonWithEdgeInsetsStyle:GLButtonEdgeInsetsStyleLeft imageTitleSpace:8];
    [backBtn addTarget:self action:@selector(backClick:) forControlEvents:UIControlEventTouchUpInside];
    
    UIBarButtonItem*backItem = [[UIBarButtonItem alloc]initWithCustomView:backBtn];
    
    self.navigationItem.leftBarButtonItem = backItem;
    
//    UIButton* bcBtn = [UIButton buttonWithType:UIButtonTypeCustom];
//   [bcBtn setTitle:@"旧版存钱罐" forState:UIControlStateNormal];
//   bcBtn.titleLabel.font = [UIFont systemFontOfSize:15];
//   [bcBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
//   bcBtn.frame = CGRectMake(0, 0, 60, 44);
//   [bcBtn layoutButtonWithEdgeInsetsStyle:GLButtonEdgeInsetsStyleLeft imageTitleSpace:8];
//   [bcBtn addTarget:self action:@selector(bcBtnClick:) forControlEvents:UIControlEventTouchUpInside];
//  
//   UIBarButtonItem*bcBtnItem = [[UIBarButtonItem alloc]initWithCustomView:bcBtn];
//  
//   self.navigationItem.rightBarButtonItem = bcBtnItem;
}

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






#pragma mark - 账户购买的产品表

#pragma mark - 根据id查询是否开通账户
- (void)queryAccountStateRequest
{
    NSString* url = [NSString stringWithFormat:@"%@%@",[NetworkConfig ipYinShuConfig],YSQueryAccountStateRequest];
    
    NSDictionary*params = @{
        @"bankName":@"乌当银行",
        @"id":@([getPeopleID PeopleID]),
        @"tel":[getPeopleID PeopleIphoneNmber]
    };
    
    NSLog(@"银数查询是否开通账户url:%@",url);
    NSLog(@"params:%@",params);
    
    //[KKLoadingAnimationView show];
    
    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) {
       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.infoModel = [SaveAccountInfoModel mj_objectWithKeyValues:dic];
            self->WDAccountOPened  = YES;
            if (self.infoModel.SUBPACKS.count > 0) {
                SaveAccountSubUserInfoModel*subUserInfo = self.infoModel.SUBPACKS[0];
                [self getPayAccountInfoRequest:subUserInfo.MO_PHONE];
                return;
            }else{
                [SVProgressHUD showErrorWithStatus:@"开通账户异常"];
            }
               
            
        }else if ([state isEqualToString:@"201"]){
            //未开户
            self->WDAccountOPened = NO;
            [self.tableView reloadData];
        }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:@"系统错误"];
           }
        }
        
        //[KKLoadingAnimationView dismiss];
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
      // [KKLoadingAnimationView dismiss];
       NSLog(@"error:%@",error);
    }];
}


#pragma mark - 获取支付账户信息
- (void)getPayAccountInfoRequest:(NSString*)bindTel
{
    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 checkYSAccountBuyedProListRequest:bindTel];
        }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) {
       //[KKLoadingAnimationView dismiss];
       NSLog(@"error:%@",error);
        [SVProgressHUD showInfoWithStatus:@"网络异常"];
    }];
}


#pragma mark - 查询银数账户购买的产品表
- (void)checkYSAccountBuyedProListRequest:(NSString*)bindTel
{
    NSString* url = [NSString stringWithFormat:@"%@%@",[NetworkConfig ipYinShuConfig],YSBuyedProListRequest];
//    NSString*phone = [getPeopleID PeopleIphoneNmber];
    NSDictionary*params = @{
        @"tel": bindTel ? bindTel :@""
    };
    
    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"]];
        NSDictionary* result = responseObject[@"result"];
        NSString*describe = [NSString stringWithFormat:@"%@",responseObject[@"describe"]];
        if ([state isEqualToString:@"200"]) {
            //NSDictionary*dic = [Tools dencode:result];
            NSLog(@"result:%@",result);
            NSMutableArray*array = [YSBuyedProModel mj_objectArrayWithKeyValuesArray:result];
            self.proArr = array;
            self->ygSum = 0.0;
            for (YSBuyedProModel* model in array) {
                self->ygSum = self->ygSum + model.account.floatValue/100;
            }
            
            if (self.bcSumAmount) {
                self.headerView.lb_amount.text = [NSString stringWithFormat:@"%.2f",self->ygSum + self.cardModel.AVAIL_BAL.floatValue + self.bcSumAmount.doubleValue];
            }else {
                self.headerView.lb_amount.text = [NSString stringWithFormat:@"%.2f",self->ygSum + self.cardModel.AVAIL_BAL.floatValue];
            }
            
            
            [self.tableView reloadData];
            return;
        }else{
            [SVProgressHUD showErrorWithStatus:describe];
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
       //[KKLoadingAnimationView dismiss];
       NSLog(@"error:%@",error);
        [SVProgressHUD showInfoWithStatus:@"网络异常"];
    }];
}

#pragma mark -比财 查询用户所有已开户的银行
- (void)bcGetAllOpenedAccountOrgs
{
    NSString* url = [NSString stringWithFormat:@"%@%@",[NetworkConfig ipYinShuConfig],BCGetOPenedAccountOrgsRequest];
    NSLog(@"比财所有已开户银行url:%@",url);
    NSMutableDictionary *params = [NetworkPublicParams getBCPublicParams];
    
    [params setObject:[getPeopleID PeopleIphoneNmber] forKey:@"loginPhoneNum"];
    
    
    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"]) {
            self.bcCardArray = [BCOPenedCardModel mj_objectArrayWithKeyValuesArray:objc[@"result"][@"banks"]];
            
            [self.tableView reloadData];
            
        }else{
            [Tools showMessage:describe];
        }

        [self.tableView reloadData];
    } Failure:^(NSError* error) {
        NSLog(@"error:%@",error);
        
        [Tools showMessage:@"网络出小差了,请稍后重试"];
        
    }];
}

#pragma mark - 查询机构列表
- (void)bcQueryOrgListRequest:(BCOPenedCardModel *)model {
    NSString* url = [NSString stringWithFormat:@"%@%@",[NetworkConfig ipYinShuConfig],BCOrgListRequest];
    NSLog(@"比财所有机构列表url:%@",url);
    NSMutableDictionary *params = [NetworkPublicParams getBCPublicParams];
    
    
    
    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"]) {
            NSArray* orgList = objc[@"result"][@"orgList"];
            for (NSDictionary* dic in orgList) {
                if ([dic[@"orgId"] isEqualToString:model.orgId]) {
                    model.bankLogUrl = dic[@"logoUrl"];
                    break;
                }
            }
            
            if ([Tools isBlankString:model.bankLogUrl]) {
                model.bankLogUrl = @"123";
            }
            
            [self.tableView beginUpdates];

            [self.tableView endUpdates];
            
        }

    } Failure:^(NSError* error) {
        NSLog(@"error:%@",error);
        
        [Tools showMessage:@"网络出小差了,请稍后重试"];
        
    }];
}


#pragma mark - 比财 资产持仓产品
- (void)bcGetEleAccountInfoRequest:(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);
    
    [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"]) {
           
            BCHoldProListModel* model = [BCHoldProListModel mj_objectWithKeyValues:objc[@"result"]];

            kmodel.subModel = model;
            
            
            [self.tableView reloadData];
            
        }
    } Failure:^(NSError* error) {
       
        NSLog(@"error:%@",error);
        
        
    }];
    
}

#pragma mark - 比财 查询整合的总金额
- (void)bcQuerySumAmountRequest
{
    NSString* url = [NSString stringWithFormat:@"%@%@",[NetworkConfig ipYinShuConfig],BCGetSumAmountRequest];
    NSLog(@"比财查询整合的总金额url:%@",url);
    NSMutableDictionary *params = [NetworkPublicParams getBCPublicParams];
    
    [params setObject:[getPeopleID PeopleIphoneNmber] forKey:@"loginPhoneNum"];
    
    
    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"]) {
           
            self.bcSumAmount = objc[@"result"][@"sumAmount"];
            
            if (self.cardModel) {
                self.headerView.lb_amount.text = [NSString stringWithFormat:@"%.2f",self->ygSum + self.cardModel.AVAIL_BAL.floatValue + self.bcSumAmount.doubleValue];
            }else{
                self.headerView.lb_amount.text = [NSString stringWithFormat:@"%.2f",self.bcSumAmount.doubleValue];
            }
            
            
        }
    } Failure:^(NSError* error) {
       
        NSLog(@"error:%@",error);
        
        
    }];
}




#pragma mark - 查看是否显示banner
- (void)checkISDisplayBottomBannerRequest
{
    NSString* url = [NSString stringWithFormat:@"%@%@",[NetworkConfig ipYinShuConfig],YSISDisplayBannerRequest];
    NSDictionary*params = @{
        @"tel":[getPeopleID PeopleIphoneNmber]
    };
    
    NSLog(@"查询是否显示底部banner的url:%@",url);
    NSLog(@"params:%@",params);
    [NetworkRequest Post:url Params:params Success:^(id _Nonnull objc) {
        NSLog(@"objc:%@",objc);
        NSString*state = [NSString stringWithFormat:@"%@",objc[@"state"]];
        if ([state isEqualToString:@"200"]) {
            NSNumber*result = objc[@"result"];
            self.bottomView.hidden = !result.boolValue;
        }
    } Failure:^(NSError* error) {
        NSLog(@"error:%@",error);
    }];
}

#pragma mark - 爱达api请求
- (NSDictionary *)aiDaTokenRequestPara
{
    NSDictionary* params = @{
        @"loginId":[NSNumber numberWithInteger:[getPeopleID PeopleID]].stringValue,
        @"telephone":[getPeopleID PeopleIphoneNmber]
    };
    return params;
}

- (void)aiDaTokenRequest:(void (^)(bool success, NSString*token))response
{
    NSString*url = [NSString stringWithFormat:@"%@%@",[NetworkConfig ipAdDaConfig],AiDaTokenRequest];
    NSLog(@"爱达token的url:%@",url);
    
    NSLog(@"params:%@",[self aiDaTokenRequestPara]);
    
    [NetworkRequest Get3:url Params:[self aiDaTokenRequestPara] Success:^(id _Nonnull responseObject) {
        
        NSLog(@"responseObject:%@",responseObject);
        
        if ([responseObject isKindOfClass:[NSDictionary class]]) {
            NSString*state = [NSString stringWithFormat:@"%@",responseObject[@"state"]];
            NSString*describe = [NSString stringWithFormat:@"%@",responseObject[@"describe"]];
            if ([state isEqualToString:@"200"]) {
                
                NSString*token = [NSString stringWithFormat:@"%@",responseObject[@"result"]];
                
                response(YES,token);
                
            }else{
                [SVProgressHUD showErrorWithStatus:describe];
            }
            
        }else{
            [SVProgressHUD showErrorWithStatus:@"服务器异常"];
        }
        
    } Failure:^(NSError * _Nonnull error) {
        NSLog(@"error:%@",error);
        [SVProgressHUD showErrorWithStatus:@"网络异常"];
    }];
}

- (NSDictionary *)aidaUrlRequestPara
{
    NSDictionary* params = @{
        @"deviceid":[[[[UIDevice currentDevice] identifierForVendor] UUIDString]stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]],
        @"mobile":[[getPeopleID PeopleIphoneNmber] stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]],
        @"uid":[NSNumber numberWithInteger:[getPeopleID PeopleID]].stringValue
    };
  
    return params;
}

- (void)aidaUrlRequestWithToken:(NSString *)token
{
    NSString*url = [NSString stringWithFormat:@"%@%@",[NetworkConfig ipAdDaUrlConfig],AiDaUrlRequest];
    NSLog(@"爱达url的url:%@",url);
    
    NSLog(@"params:%@",[self aidaUrlRequestPara]);
    
    [NetworkRequest Post5:url Params:[self aidaUrlRequestPara] Token:token Success:^(id  _Nonnull responseObject) {
        
         NSLog(@"responseObject:%@",responseObject);
        
        if ([responseObject isKindOfClass:[NSDictionary class]]) {
            NSString*state = [NSString stringWithFormat:@"%@",responseObject[@"state"]];
            NSString*describe = [NSString stringWithFormat:@"%@",responseObject[@"describe"]];
            if ([state isEqualToString:@"200"]) {
                
                NSString*url = [NSString stringWithFormat:@"%@",responseObject[@"result"]];
                
//                NSMutableCharacterSet *lastSet = [[NSMutableCharacterSet alloc] init];
//                   [lastSet formUnionWithCharacterSet:[NSCharacterSet characterSetWithCharactersInString:@"-_.!~*;/?:@&=$,#"]];
//                   [lastSet formUnionWithCharacterSet:[NSCharacterSet letterCharacterSet]];
//                   [lastSet formUnionWithCharacterSet:[NSCharacterSet alphanumericCharacterSet]];
//
//                url = [url stringByAddingPercentEncodingWithAllowedCharacters:lastSet];
                
                if ([self.navigationController.visibleViewController isKindOfClass:[MyAssetsController class]]) {
                    Web2ViewController * vc = [Web2ViewController new];
                    vc.title= @"智能问诊";
                    vc.skipUrl = [NSURL URLWithString:url];
                    vc.hidesBottomBarWhenPushed = YES;
                    [self.navigationController pushViewController:vc animated:YES];
                }
                
              
                
                
            }else{
                [SVProgressHUD showErrorWithStatus:describe];
            }
            
        }else{
            [SVProgressHUD showErrorWithStatus:@"服务器异常"];
        }
        
    } Failure:^(NSError * _Nonnull error) {
        
        NSLog(@"error:%@",error);
        [SVProgressHUD showErrorWithStatus:@"网络异常"];
        
    }];
}

#pragma mark - 比财

- (NSDictionary *)getBCRequestParamWithOrgId:(NSString *)orgId
{
    NSDictionary *params = @{
        @"phone":[[getPeopleID PeopleIphoneNmber] stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]],
        @"orgId":orgId
    };
    return params;
}

- (void)getBCRequest:(NSString *)token orgId:(NSString *)orgId
{
   NSString*url = [NSString stringWithFormat:@"%@%@/org",[NetworkConfig ipAdDaUrlConfig],BCUrlRequest];
    NSLog(@"比财url的url:%@",url);
    
    NSLog(@"params:%@",[self getBCRequestParam]);
    
    [NetworkRequest Get2:url Params:[self getBCRequestParamWithOrgId:orgId] Token:token Success:^(id  _Nonnull responseObject) {
        
         NSLog(@"responseObject:%@",responseObject);
                
        if ([responseObject isKindOfClass:[NSDictionary class]]) {
            NSString*state = [NSString stringWithFormat:@"%@",responseObject[@"state"]];
            NSString*describe = [NSString stringWithFormat:@"%@",responseObject[@"describe"]];
            if ([state isEqualToString:@"200"]) {
                NSString*url = [NSString stringWithFormat:@"%@&appBarHide=hide",responseObject[@"result"]];
                Web2ViewController * vc = [Web2ViewController new];
                vc.title= @"存钱罐";
                vc.skipUrl = [NSURL URLWithString:url];
                vc.hidesBottomBarWhenPushed = YES;
                [self.navigationController pushViewController:vc animated:YES];
              
                
                
            }else{
                [SVProgressHUD showErrorWithStatus:describe];
            }
            
        }else{
            [SVProgressHUD showErrorWithStatus:@"服务器异常"];
        }
        
        
    } Failure:^(NSError * _Nonnull error) {
        NSLog(@"error:%@",error);
        [SVProgressHUD showErrorWithStatus:@"网络异常"];
    }];
}



#pragma mark - 比财

- (NSDictionary *)getBCRequestParam
{
    NSDictionary *params = @{
        @"phone":[[getPeopleID PeopleIphoneNmber] stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]],
        @"id":[NSNumber numberWithInteger:[getPeopleID PeopleID]].stringValue
    };
    return params;
}

- (void)getBCRequest:(NSString *)token
{
   NSString*url = [NSString stringWithFormat:@"%@%@",[NetworkConfig ipAdDaUrlConfig],BCUrlRequest];
    NSLog(@"比财url的url:%@",url);
    
    NSLog(@"params:%@",[self getBCRequestParam]);
    
    [NetworkRequest Get2:url Params:[self getBCRequestParam] Token:token Success:^(id  _Nonnull responseObject) {
        
         NSLog(@"responseObject:%@",responseObject);
                
        if ([responseObject isKindOfClass:[NSDictionary class]]) {
            NSString*state = [NSString stringWithFormat:@"%@",responseObject[@"state"]];
            NSString*describe = [NSString stringWithFormat:@"%@",responseObject[@"describe"]];
            if ([state isEqualToString:@"200"]) {
                
                NSString*url = [NSString stringWithFormat:@"%@&appBarHide=hide",responseObject[@"result"]];
                
//                NSMutableCharacterSet *lastSet = [[NSMutableCharacterSet alloc] init];
//                   [lastSet formUnionWithCharacterSet:[NSCharacterSet characterSetWithCharactersInString:@"-_.!~*;/?:@&=$,#"]];
//                   [lastSet formUnionWithCharacterSet:[NSCharacterSet letterCharacterSet]];
//                   [lastSet formUnionWithCharacterSet:[NSCharacterSet alphanumericCharacterSet]];
//
//                url = [url stringByAddingPercentEncodingWithAllowedCharacters:lastSet];
                
                if ([self.navigationController.visibleViewController isKindOfClass:[MyAssetsController class]]) {
                    Web2ViewController * vc = [Web2ViewController new];
                    vc.title= @"存钱罐";
                    vc.skipUrl = [NSURL URLWithString:url];
                    vc.hidesBottomBarWhenPushed = YES;
                    [self.navigationController pushViewController:vc animated:YES];
                }
                
              
                
                
            }else{
                [SVProgressHUD showErrorWithStatus:describe];
            }
            
        }else{
            [SVProgressHUD showErrorWithStatus:@"服务器异常"];
        }
        
        
    } Failure:^(NSError * _Nonnull error) {
        NSLog(@"error:%@",error);
        [SVProgressHUD showErrorWithStatus:@"网络异常"];
    }];
}



#pragma mark - UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1 + self.bcCardArray.count;
}

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


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    OPenBankListCell*cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    
    if (indexPath.section == 0) {
        cell.icon.image = [UIImage imageNamed:@"bank_wudang"];
        cell.lb_name.text = @"乌当农商银行";
        cell.lb_message.text = @"隶属于贵州乌当农商银行";
        if (WDAccountOPened) {
            [cell.checkBtn setTitle:@"查看资产" forState:UIControlStateNormal];
            cell.lb_ye.text = [NSString stringWithFormat:@"%.2f",self.cardModel.AVAIL_BAL.doubleValue];
            cell.lb_yg.text = [NSString stringWithFormat:@"%.2f",ygSum];
        }else{
            [cell.checkBtn setTitle:@"立即开户" forState:UIControlStateNormal];
            cell.lb_ye.text = @"--";
            cell.lb_yg.text = @"--";
            
            
        }
        
    }else{
        BCOPenedCardModel* model = self.bcCardArray[indexPath.section - 1];
        [cell.icon sd_setImageWithURL:[NSURL URLWithString:model.bankLogUrl] completed:nil];
        cell.lb_name.text = model.bankName;
        cell.lb_message.text = [NSString stringWithFormat:@"隶属于%@",model.bankName];
        if ([model.isOpenAccount isEqualToString:@"1"]) {
            [cell.checkBtn setTitle:@"查看资产" forState:UIControlStateNormal];
            cell.lb_ye.text = model.balance;
            cell.lb_yg.text = model.holdAmount;
            
//            if (model.subModel == nil) {
//                cell.lb_yg.text = @"--";
//                [self bcGetEleAccountInfoRequest:model];
//            }else{
//                cell.lb_yg.text = model.subModel.totalHoldAmount;
//            }
        }else{
            [cell.checkBtn setTitle:@"立即开户" forState:UIControlStateNormal];
            cell.lb_ye.text = @"--";
            cell.lb_yg.text = @"--";
            if ([Tools isBlankString:model.bankLogUrl]) {
                [self bcQueryOrgListRequest:model];
            }
        }
       
    }
    
    
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 10.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 (indexPath.section == 0) {
        
        if (WDAccountOPened) {
            if (self.cardModel == nil && self.infoModel == nil) {
                [SVProgressHUD showErrorWithStatus:@"网络异常"];
                [self queryAccountStateRequest];
                return;
            }
            MyBankDetailController*detailVC = [MyBankDetailController new];
            detailVC.hidesBottomBarWhenPushed  = YES;
            detailVC.title = @"存钱罐";
            detailVC.infoModel = self.infoModel;
            detailVC.cardModel = self.cardModel;
            detailVC.proSum = ygSum;
            detailVC.proArr = self.proArr;
            [self.navigationController pushViewController:detailVC animated:YES];
        }else{
            OPenAccountController*vc = [OPenAccountController new];
            vc.title = @"存钱罐开户";
               //vc.productModel = self.model;
            vc.hidesBottomBarWhenPushed = YES;
            [self.navigationController pushViewController:vc animated:YES];
        }
        
    }else {
        BCOPenedCardModel* model = self.bcCardArray[indexPath.section - 1];
        
        if ([model.isOpenAccount isEqualToString:@"1"]) {
            
            if (model.app == NO) {
                [self aiDaTokenRequest:^(bool success, NSString *token) {
                       [self getBCRequest:token orgId:model.orgId];
                }];
                
                
            }else{
                MyBankDetailController*detailVC = [MyBankDetailController new];
                detailVC.hidesBottomBarWhenPushed  = YES;
                detailVC.title = @"存钱罐";
                detailVC.type = SaveFromTypeBiCai;
                detailVC.bcCardModel = model;
                [self.navigationController pushViewController:detailVC animated:YES];
               
            }
            
        }else if ([model.isOpenAccount isEqualToString:@"0"]) {
            UIAlertController * alertV = [UIAlertController alertControllerWithTitle:@"提示" message:@"该银行还未开户,请在产品列表中选择该银行的一个产品去开户" preferredStyle:UIAlertControllerStyleAlert];
            
            UIAlertAction *confirm = [UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                self.navigationController.tabBarController.selectedIndex = 0;
            }];
            
            UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
                
            }];
            
            [alertV addAction:cancel];
            [alertV addAction:confirm];
            
            [self presentViewController:alertV animated:YES completion:nil];
        }
        
       
    }
    
   
}



#pragma mark - public methods
-(id)getXiblWithClassName:(NSString *)className
{
    return [[NSBundle mainBundle]loadNibNamed:className owner:self options:nil].lastObject;
}
#pragma mark - event response
- (void)backClick:(UIButton *)sender
{
    [self.tabBarController.navigationController popViewControllerAnimated:YES];
}
- (void)checkQRBtnClick:(UIButton *)sender
{
    [SaveWelfareAlertView showAlertViewWithVC:self];
}
- (void)bcBtnClick:(UIButton *)sender
{
    WeakSelf
       if (![[NSUserDefaults standardUserDefaults]boolForKey:@"bicai_allow"]) {
                      
              
           [AiDaAlertView showAlertViewWithTitle:@"比财数据" imageName:@"bicailogo" ViewController:self type:AiDaAlertViewTypeBC block:^(BOOL success) {
               [[NSUserDefaults standardUserDefaults]setBool:YES forKey:@"bicai_allow"];
               [[NSUserDefaults standardUserDefaults]synchronize];
               [weakSelf aiDaTokenRequest:^(bool success, NSString *token) {
                   [weakSelf getBCRequest:token];
                  
               }];
           }];
           
            return;
                     
       }
       
        [self aiDaTokenRequest:^(bool success, NSString *token) {
               [weakSelf getBCRequest:token];
        }];
}

#pragma mark - getters
- (UITableView *)tableView
{
    if (!_tableView) {
        _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, ScreenHeight - cl_kTabBarHeight) style:UITableViewStyleGrouped];
        _tableView.delegate =self;
        _tableView.dataSource = self;
        _tableView.rowHeight = UITableViewAutomaticDimension;
        _tableView.estimatedRowHeight = 50;
        _tableView.estimatedSectionHeaderHeight = 10.0;
        _tableView.estimatedSectionHeaderHeight = 10.0;
        [_tableView registerNib:[UINib nibWithNibName:@"OPenBankListCell" bundle:nil] forCellReuseIdentifier:@"cell"];
        _tableView.bounces = NO;
        
        self.headerView = [self getXiblWithClassName:@"MyAssetsTopView"];
        self.headerView.backgroundColor = [UIColor colorWithHex:0x137ef6];
        _tableView.tableHeaderView = self.headerView;
    }
    return _tableView;
}

- (UIView *)bottomView
{
    if (!_bottomView) {
        _bottomView = [[UIView alloc]initWithFrame:CGRectMake((ScreenWidth - 355 * WIDTHRADIU)/2, ScreenHeight - cl_kTabBarHeight - 90                                                                                                      * WIDTHRADIU , 355 * WIDTHRADIU, 75 * WIDTHRADIU)];
        
        UIImageView*imageView = [[UIImageView alloc]initWithFrame:_bottomView.bounds];
        imageView.image = [UIImage imageNamed:@"save_bottomBanner"];
        [_bottomView addSubview:imageView];
        
        UIButton*checkQRBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        checkQRBtn.frame = imageView.frame;
        [checkQRBtn addTarget:self action:@selector(checkQRBtnClick:) forControlEvents:UIControlEventTouchUpInside];
        [_bottomView addSubview:checkQRBtn];
        _bottomView.hidden = YES;
    }
    return _bottomView;
}

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