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

#import "SaveSettingController.h"
#import "SaveSettingCell.h"
#import "SavePhoneModtifyController.h"
#import "SaveAccountCardInfo.h"
#import "YSBuyedProModel.h"
#import "KBankListModel.h"
#import "SaveCardMoftifyController.h"

#import "SaveSettingSuccessController.h"

@interface SaveSettingController ()<UITableViewDelegate,UITableViewDataSource>

@property (nonatomic, strong)UITableView* tableView;

@property (nonatomic, strong)NSArray* titleArray;

@property (nonatomic, strong)SaveAccountCardInfo* cardModel;

@property (nonatomic, strong)NSArray*proArr;

@property (nonatomic, strong)UILabel* lb_message;


@end

@implementation SaveSettingController
- (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_wudangServiceMoreCount" withArgs:nil];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor colorWithHex:0xf4f4f4];
    [self.view addSubview:self.tableView];
    [self.view addSubview:self.lb_message];
    
}




#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);
    [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.cardModel = [SaveAccountCardInfo mj_objectWithKeyValues:dic];
            [self checkYSAccountBuyedProListRequest];
            return;
        }
        [KKLoadingAnimationView dismiss];
        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* url = [NSString stringWithFormat:@"%@%@",[NetworkConfig ipYinShuConfig],YSBuyedProListRequest];
     NSString*phone = [getPeopleID PeopleIphoneNmber];
   NSDictionary*params = @{
       @"tel": ![Tools isBlankString:phone] ? phone :@""
   };
    
    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*describe = [NSString stringWithFormat:@"%@",responseObject[@"describe"]];
        NSDictionary* result = responseObject[@"result"];
        if ([state isEqualToString:@"200"]) {
            //NSDictionary*dic = [Tools dencode:result];
            NSLog(@"result:%@",result);
            NSMutableArray*array = [YSBuyedProModel mj_objectArrayWithKeyValuesArray:result];
            self.proArr = array;
            
            if (self.proArr.count == 0 && self.cardModel.AVAIL_BAL.doubleValue <=0) {
                SaveCardMoftifyController*vc = [SaveCardMoftifyController new];
                vc.title = @"更换绑定银行卡";
                vc.infoModel = self.infoModel;
                [self.navigationController pushViewController:vc animated:YES];
                
                return;
            }else{
                UIAlertController* alertVC = [UIAlertController alertControllerWithTitle:nil message:@"电子账户有余额或有已购产品,请提现或赎回后重试" preferredStyle:UIAlertControllerStyleAlert];
                UIAlertAction* confirmAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                
                }];
                [alertVC addAction:confirmAction];
                
                [self presentViewController:alertVC animated:YES completion:nil];
            }
            
            return;
        }else{
            [SVProgressHUD showErrorWithStatus:describe];
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
       [KKLoadingAnimationView dismiss];
       NSLog(@"error:%@",error);
         [SVProgressHUD showInfoWithStatus:@"网络异常"];
    }];
}

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

// Row display. Implementers should *always* try to reuse cells by setting each cell's reuseIdentifier and querying for available reusable cells with dequeueReusableCellWithIdentifier:
// Cell gets various attributes set automatically based on table (separators) and data source (accessory views, editing controls)

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    if (self.type == SaveFromTypeBiCai) {
        BCCardListModel *ccmodel = nil;
        if (self.bcAccountModel.cardList.count > 0) {
            ccmodel = self.bcAccountModel.cardList[0];
        }
        
        SaveSettingCell*cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
        
        cell.lb_title.text = self.titleArray[indexPath.section];
        if (indexPath.section == 0) {
            cell.lb_content.hidden = NO;
            cell.lb_content.text = [NSString stringWithFormat:@"%@%@",ccmodel.bankName,ccmodel.lastFourCardNo];
        }else if (indexPath.section == 1){
            cell.lb_content.hidden = NO;
            cell.lb_content.text = [NSString stringWithFormat:@"%@****%@",[ccmodel.bankCardPhone substringToIndex:3],[ccmodel.bankCardPhone substringFromIndex:ccmodel.bankCardPhone.length - 4]];
        }else if (indexPath.section == 2){
            cell.lb_content.hidden = YES;
        }else if (indexPath.section == 3){
            cell.lb_content.hidden = NO;
            cell.lb_content.text = self.bcAccountModel.custServiceHotLine[0];
        }
        
        return cell;
    }
    SaveAccountSubUserInfoModel*userInfo = self.infoModel.SUBPACKS[0];
    SaveSettingCell*cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    
    cell.lb_title.text = self.titleArray[indexPath.section];
    if (indexPath.section == 0) {
        cell.lb_content.hidden = NO;
        cell.lb_content.text = [NSString stringWithFormat:@"%@(%@)",[self returnBankName:userInfo.SIGCARD],[userInfo.SIGCARD substringFromIndex:userInfo.SIGCARD.length - 4]];
    }else if (indexPath.section == 1){
        cell.lb_content.hidden = NO;
        cell.lb_content.text = [NSString stringWithFormat:@"%@****%@",[userInfo.MO_PHONE substringToIndex:3],[userInfo.MO_PHONE substringFromIndex:userInfo.MO_PHONE.length - 4]];
    }else if (indexPath.section == 2){
        cell.lb_content.hidden = YES;
    }else if (indexPath.section == 3){
        cell.lb_content.hidden = NO;
        cell.lb_content.text = @"400-686-8707";
    }else if (indexPath.section == 4){
        cell.lb_content.hidden = YES;
    }else if (indexPath.section == 5){
        cell.lb_content.hidden = NO;
        cell.lb_content.text = @"银行说明";
    }
   
    
    
    return cell;
}

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

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 60;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    if (self.type == SaveFromTypeBiCai) {
        BCCardListModel *ccmodel = nil;
        if (self.bcAccountModel.cardList.count > 0) {
            ccmodel = self.bcAccountModel.cardList[0];
        }
        
        if (indexPath.section == 0) {
            [self alertShow:@"暂不支持更换绑定卡!"];
            return;
        }else if (indexPath.section == 1){
            [self alertShow:@"暂不支持更换手机号!"];
            return;
        }else if (indexPath.section == 2){
            UIAlertController* alertVC = [UIAlertController alertControllerWithTitle:nil message:self.bcAccountModel.bankElecAccountNum preferredStyle:UIAlertControllerStyleAlert];
            UIAlertAction*cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
            UIAlertAction* confirmAction = [UIAlertAction actionWithTitle:@"复制卡号" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
                pasteboard.string = self.bcAccountModel.bankElecAccountNum;
                [Tools showMessage:@"复制成功"];
            }];
            
            [alertVC addAction:cancelAction];
            [alertVC addAction:confirmAction];
            
            [self presentViewController:alertVC animated:YES completion:nil];
        }else if (indexPath.section == 3) {
            if (![Tools isBlankString:self.bcAccountModel.custServiceHotLine[0]]) {
                NSMutableString *str=[[NSMutableString alloc] initWithFormat:@"telprompt://%@",self.bcAccountModel.custServiceHotLine[0]];
                [[UIApplication sharedApplication] openURL:[NSURL URLWithString:str]];
            }else{
                [Tools showMessage:@"暂无客服电话"];
            }
            
           

            
        }
        
        
        return;
        
    }
    
    SaveAccountSubUserInfoModel*userInfo = self.infoModel.SUBPACKS[0];
    if (indexPath.section == 0) {
        [self getPayAccountInfoRequest];
    }else if (indexPath.section == 1){
        
        SavePhoneModtifyController* vc = [SavePhoneModtifyController new];
        vc.title = @"修改预留手机号";
        vc.infoModel = self.infoModel;
        [self.navigationController pushViewController:vc animated:YES];
    }else if (indexPath.section == 2){
        UIAlertController* alertVC = [UIAlertController alertControllerWithTitle:nil message:userInfo.CARDNBR preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction*cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
        UIAlertAction* confirmAction = [UIAlertAction actionWithTitle:@"复制卡号" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
            pasteboard.string = userInfo.CARDNBR;
            [Tools showMessage:@"复制成功"];
        }];
        
        [alertVC addAction:cancelAction];
        [alertVC addAction:confirmAction];
        
        [self presentViewController:alertVC animated:YES completion:nil];
    }else if (indexPath.section == 3){
        NSMutableString *str=[[NSMutableString alloc] initWithFormat:@"telprompt://%@",@"400-686-8707"];

        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:str]];

    }else if (indexPath.section == 4){
        UIAlertController* alertVC = [UIAlertController alertControllerWithTitle:nil message:@"乌当农商银行电子账户是电子化的个人银行类Ⅱ账户,目前在看看生活平台用户在银行旗下申购和赎回的理财产品,资金交易安全有保障" preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction* confirmAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        }];
        [alertVC addAction:confirmAction];
        
        [self presentViewController:alertVC animated:YES completion:nil];
    }else if (indexPath.section == 5){
        [self jumpToHTML5:@"http://nginx.weface.com.cn/agreement/gzwdjj.html" andJAnalytics:@"银行介绍"];
    }
}

#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 - 跳转h5页面

-(void)jumpToHTML5:(NSString*)url andJAnalytics:(NSString*)janalytics
{
    WebViewController *tc=[WebViewController new];
    tc.URL =[NSURL URLWithString:url];
    tc.hidesBottomBarWhenPushed =YES;
    tc.janalytics = janalytics;
    [self.navigationController pushViewController:tc animated:YES];

}

#pragma mark - 根据卡号获取银行名称
//根据卡号判断银行
- (NSString *)returnBankName:(NSString *)cardName {
    
    
    if (cardName.length < 6) {
        return @"";
    }
    NSString*bankName = [KBankListModel getBankNameWithStr:cardName];
    
    return bankName;
    
}

#pragma mark - getters and setters
- (UITableView *)tableView
{
    if (!_tableView) {
        CGFloat bottomSpace = 0.0;
        if (cl_kNavigationBarHeight > 64) {
            bottomSpace = 20;
        }
        _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, cl_kNavigationBarHeight, ScreenWidth, ScreenHeight - cl_kNavigationBarHeight- 20 * WIDTHRADIU - bottomSpace) style:UITableViewStyleGrouped];
        _tableView.showsVerticalScrollIndicator = NO;
        _tableView.dataSource = self;
        _tableView.delegate = self;
        _tableView.backgroundColor = [UIColor colorWithHex:0xf4f4f4];
        _tableView.estimatedSectionFooterHeight = 10;
        _tableView.estimatedSectionHeaderHeight = 10;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        [_tableView registerNib:[UINib nibWithNibName:@"SaveSettingCell" bundle:nil] forCellReuseIdentifier:@"cell"];
    }
    return _tableView;
}

- (UILabel *)lb_message
{
    if (!_lb_message) {
        CGFloat bottomSpace = 0.0;
        if (cl_kNavigationBarHeight > 64) {
            bottomSpace = 20;
        }
        _lb_message = [[UILabel alloc]initWithFrame:CGRectMake(0, ScreenHeight - 20 * WIDTHRADIU - bottomSpace, ScreenWidth, 20 * WIDTHRADIU)];
        _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.bcAccountModel.orgName];
        }else if (self.type == SaveFromTypeYinShu) {
            _lb_message.text = @"本产品服务由贵州乌当农商银行提供";
        }
        
    }
    return _lb_message;
}

- (NSArray *)titleArray
{
    if (!_titleArray) {
        if (self.type == SaveFromTypeBiCai) {
            _titleArray = @[@"绑定银行卡",@"预留手机号",@"查看完整卡号",@"银行客服"];
        }else{
        _titleArray = @[@"绑定银行卡",@"预留手机号",@"查看完整卡号",@"银行客服",@"电子账户说明",@"关于乌当农商银行"];
        }
    }
    return _titleArray;
}

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