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

#import "SaveWithDrawController.h"
#import "RechargeTopView.h"
#import "SaveWithDrawInputView.h"
#import "SaveWithDrawBankView.h"
#import "UIView+frameAdjust.h"
#import <YYLabel.h>
#import <YYText.h>
#import "UIImageView+WebCache.h"
#import "SMSVerificationController.h"
#import "KBankListModel.h"


@interface SaveWithDrawController ()<UITextFieldDelegate>

@property (nonatomic, assign)BOOL textIsEmpty;

@property (nonatomic, strong)UIScrollView* scrollView;

@property (nonatomic, strong)RechargeTopView* topView;

@property (nonatomic, strong)SaveWithDrawInputView* inputView;

@property (nonatomic, strong)UIButton* payBtn;

@end

@implementation SaveWithDrawController
- (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_wudangTXCount" withArgs:nil];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor whiteColor];
    
    [self.view addSubview:self.scrollView];
    
    //初始化
    self.textIsEmpty = YES;
    [self setButtonState];
    
    if (self.type == SaveFromTypeBiCai) {
        
    }else {
        //检测产品购买
        [[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.topView.lb_money.text = [NSString stringWithFormat:@"%.2f",self.cardModel.AVAIL_BAL.doubleValue];
}




#pragma mark - UITextFieldDelegate
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    NSMutableString * changedString=[[NSMutableString alloc] initWithString:textField.text];
    [changedString replaceCharactersInRange:range withString:string];
  
    NSString * str = [NSString stringWithFormat:@"%@%@",textField.text,string];
    //匹配以0开头的数字
    NSPredicate * predicate0 = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",@"^[0][0-9]+$"];
    //匹配两位小数、整数
    NSPredicate * predicate1 = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",@"(\\+|\\-)?(([0]|(0[.]\\d{0,3}))|([1-9]\\d{0,7}(([.]\\d{0,2})?)))?"];
    BOOL sucess = ![predicate0 evaluateWithObject:str] && [predicate1 evaluateWithObject:str] &&[self validateNumber:string] ? YES : NO;
    
    
    if (sucess) {
        if (changedString.length == 0) {
             self.textIsEmpty = YES;
         }else{
             self.textIsEmpty = NO;
         }

        // 实时监测文本框的编辑状态
         [self setButtonState];
    }
    
    return sucess;
}


- (BOOL)validateNumber:(NSString*)number {
    BOOL res = YES;
    NSCharacterSet* tmpSet = [NSCharacterSet characterSetWithCharactersInString:@"0123456789"];
    int i = 0;
    while (i < number.length) {
        NSString * string = [number substringWithRange:NSMakeRange(i, 1)];
        NSRange range = [string rangeOfCharacterFromSet:tmpSet];
        if (range.length == 0) {
            res = NO;
            break;
        }
        i++;
    }
    return res;
}

#pragma mark - 刷新按钮状态
- (void)setButtonState {
    if (self.textIsEmpty == NO) {
        self.payBtn.userInteractionEnabled = YES;
        self.payBtn.alpha = 1;
    } else {
        self.payBtn.userInteractionEnabled = NO;
        self.payBtn.alpha = 0.5;
    }
}


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

#pragma mark - event response
- (void)allBtnClick:(UIButton *)sender
{
    if (self.type == SaveFromTypeBiCai) {
        
        if (self.bcAccountInfoModel.balance.doubleValue <= 0) {
            [self alertShow:@"电子账户余额不足"];
            return;
        }
        
        self.inputView.tf_input.text = [NSString stringWithFormat:@"%@",self.bcAccountInfoModel.balance];
        self.textIsEmpty = NO;
        [self setButtonState];
    }else {
        
        if (self.cardModel.AVAIL_BAL.doubleValue <= 0) {
            [self alertShow:@"电子账户余额不足"];
            return;
        }
        
        self.inputView.tf_input.text = [NSString stringWithFormat:@"%.2f",self.cardModel.AVAIL_BAL.doubleValue];
        self.textIsEmpty = NO;
        [self setButtonState];
    }
   
}
- (void)payBtnClick:(UIButton *)sender
{
    if (self.type == SaveFromTypeBiCai) {
        
        if (self.inputView.tf_input.text.doubleValue > self.bcAccountInfoModel.balance.doubleValue) {
            [Tools showMessage:@"余额不足"];
            return;
        }
        
        SMSVerificationController*vc = [SMSVerificationController new];
        vc.title = @"提现短信验证";
        vc.bcAccountInfoModel = self.bcAccountInfoModel;
        vc.amount = self.inputView.tf_input.text;
        vc.type = SMSSendTypeBCWithDrawal;
        [self.navigationController pushViewController:vc animated:YES];
    }else{
           [GTCountSDK trackCountEvent:@"save_wudangTXSMSCount" withArgs:nil];
           SMSVerificationController*vc = [SMSVerificationController new];
           vc.title = @"提现短信验证";
           vc.infoModel = self.infoModel;
           vc.amount = self.inputView.tf_input.text;
           vc.type = SMSSendTypeWithDrawal;
           [self.navigationController pushViewController:vc animated:YES];
           return;
    }
    
}

#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 - 根据银行卡号判断银行名称
//根据卡号判断银行
- (NSString *)returnBankName:(NSString *)cardName {
    
    
    if (cardName.length < 6) {
        return @"";
    }
    NSString*bankName = [KBankListModel getBankNameWithStr:cardName];
    
    return bankName;
    
}

#pragma mark - getters
- (UIScrollView *)scrollView
{
    if (!_scrollView) {
        _scrollView = [[UIScrollView alloc]initWithFrame:CGRectMake(0, cl_kNavigationBarHeight, ScreenWidth, ScreenHeight - cl_kNavigationBarHeight)];
        _scrollView.showsVerticalScrollIndicator = NO;
        //_scrollView.delegate = self;
        _scrollView.contentSize = CGSizeMake(ScreenWidth, 0);
        _scrollView.backgroundColor  = [UIColor colorWithHex:0xf4f4f4];
        
        //银行信息
        RechargeTopView* topView = [[RechargeTopView alloc]init];
        [_scrollView addSubview:topView];
        self.topView = topView;
        
        
        

        
        //充值金额
        SaveWithDrawInputView* valueView = [self getXiblWithClassName:@"SaveWithDrawInputView"];
        valueView.lb_title.text = @"提现金额";
        valueView.tf_input.font = [UIFont boldSystemFontOfSize:19];
        valueView.tf_input.delegate = self;
        [valueView.allBtn addTarget:self action:@selector(allBtnClick:) forControlEvents:UIControlEventTouchUpInside];
        self.inputView = valueView;
        [_scrollView addSubview:valueView];
        [valueView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(topView.mas_bottom).offset(0);
            make.left.mas_equalTo(0);
            make.width.mas_equalTo(ScreenWidth);
            make.height.mas_greaterThanOrEqualTo(50);
        }];

        
        //支付方式
        SaveWithDrawBankView* payView = [self getXiblWithClassName:@"SaveWithDrawBankView"];
        [_scrollView addSubview:payView];
        [payView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(valueView.mas_bottom).offset(10 * WIDTHRADIU);
            make.left.mas_equalTo(0);
            make.width.mas_equalTo(ScreenWidth);
            make.height.mas_greaterThanOrEqualTo(50);
            //make.bottom.mas_equalTo(0);
        }];
        
        
        
        
        //确认充值
        UIButton* payBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        payBtn.backgroundColor = [UIColor colorWithHex:0x137ef6];
        [payBtn setTitle:@"提现" forState:UIControlStateNormal];
        [payBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        payBtn.layer.cornerRadius = 5;
        [payBtn addTarget:self action:@selector(payBtnClick:) forControlEvents:UIControlEventTouchUpInside];
        self.payBtn = payBtn;
        [_scrollView addSubview:payBtn];
        
        [payBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(payView.mas_bottom).offset(40 * WIDTHRADIU);
            make.left.mas_equalTo(10 * WIDTHRADIU);
            make.width.mas_equalTo(ScreenWidth - 20 * WIDTHRADIU);
            make.height.offset(45);
        }];
        
        //1. 创建属性字符串。
       UIColor *color = [UIColor colorWithHex:0x808080];
        NSDictionary *attributes = @{NSFontAttributeName:[UIFont fontWithName:@"PingFangSC-Regular" size:12], NSForegroundColorAttributeName: color};
        
        NSMutableAttributedString *text = [[NSMutableAttributedString alloc] initWithString:@"如有疑问，请联系银行客服" attributes:attributes];
        //设置高亮色和点击事件
        [text yy_setTextHighlightRange:[[text string] rangeOfString:@"请联系银行客服"] color:[UIColor colorWithHex:0x137ef6] backgroundColor:[UIColor clearColor] tapAction:^(UIView * _Nonnull containerView, NSAttributedString * _Nonnull text, NSRange range, CGRect rect) {
            NSLog(@"点击了《用户协议》");
            if (self.type == SaveFromTypeBiCai) {
                if (self.bcAccountInfoModel.custServiceHotLine.count > 0) {
                    NSString *callPhone = [NSString stringWithFormat:@"telprompt:%@",self.bcAccountInfoModel.custServiceHotLine[0]];
                    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:callPhone]];
                }else{
                    [Tools showMessage:@"暂无客服电话"];
                }
            }else{
                NSString *callPhone = @"telprompt:400-686-8707";
                [[UIApplication sharedApplication] openURL:[NSURL URLWithString:callPhone]];
            }
            
        }];
        //提示
        YYLabel *label = [YYLabel new];
        label.attributedText = text;
        label.textAlignment = NSTextAlignmentCenter;
        [_scrollView addSubview:label];
       
        
        
        if (self.type == SaveFromTypeBiCai) {
            topView.lb_bankName.text = self.bcAccountInfoModel.orgName;
            topView.lb_mark.text = [self.bcAccountInfoModel.orgName substringToIndex:1];
            topView.lb_money.text = [NSString stringWithFormat:@"余额:%@元",self.bcAccountInfoModel.balance];
            topView.lb_number.text = [NSString stringWithFormat:@"****  %@",[self.bcAccountInfoModel.bankElecAccountNum substringFromIndex:self.bcAccountInfoModel.bankElecAccountNum.length - 4]];
            valueView.tf_input.placeholder = [NSString stringWithFormat:@"提现最小%@元,最大%@元",self.bcAccountInfoModel.withdrawMinLimitAmt,self.bcAccountInfoModel.withdrawMaxLimitAmt];
            BCCardListModel* cardModel = self.bcAccountInfoModel.cardList[0];
            
            
            
            payView.lb_bankName.text =[NSString stringWithFormat:@"%@%@",cardModel.bankName,cardModel.lastFourCardNo];
            if ([Tools isBlankString:cardModel.bankCardQuotaDescDto.singleDedctDesc]) {
                payView.lb_amount.text = @"无限额";
            }else{
                payView.lb_amount.text = [NSString stringWithFormat:@"%@,%@",cardModel.bankCardQuotaDescDto.singleDedctDesc,cardModel.bankCardQuotaDescDto.dayDedctDesc];
            }
            
            [payView.icon sd_setImageWithURL:[NSURL URLWithString:cardModel.bankLogoUrl] completed:nil];
        }else{
            topView.lb_money.text = [NSString stringWithFormat:@"余额:%.2f元",self.cardModel.AVAIL_BAL.doubleValue];
            topView.lb_number.text = [NSString stringWithFormat:@"****  %@",[self.cardModel.CARDNBR substringFromIndex:self.cardModel.CARDNBR.length - 4]];
            valueView.tf_input.placeholder = @"请输入提现金额";
            
            SaveAccountSubUserInfoModel*kModel = self.infoModel.SUBPACKS[0];
                   
            NSString* plistPath = [[NSBundle mainBundle] pathForResource:@"wdBankList"ofType:@"plist"];
            NSArray*array = [NSArray arrayWithContentsOfFile:plistPath];
            SaveBankModel*model = [SaveBankModel new];
            for (NSDictionary*dic in array) {
                if ([[self returnBankName:kModel.SIGCARD] isEqualToString:dic[@"bankName"]]) {
                    model = [SaveBankModel new];
                    model.bankName = dic[@"bankName"];
                    model.bankImage = dic[@"bankImage"];
                    model.orderMin = dic[@"orderMin"];
                    model.dMin = dic[@"dMin"];
                    break;
                }
            }
            
            payView.lb_bankName.text =[NSString stringWithFormat:@"%@(%@)",[self returnBankName:kModel.SIGCARD],[kModel.SIGCARD substringFromIndex:(kModel.SIGCARD.length - 4)]];
            if ([Tools isBlankString:model.orderMin]) {
                payView.lb_amount.text = @"单笔扣款限额1000万元,每日扣款限额1000万元";
            }else{
                payView.lb_amount.text = [NSString stringWithFormat:@"单笔扣款限额%@万元,每日扣款限额%@万元",model.orderMin,model.dMin];
            }
            
            if ([Tools isBlankString:model.bankImage]) {
                payView.icon.image = [UIImage imageNamed:@"bank_wudang"];
            }else{
                payView.icon.image = [UIImage imageNamed:model.bankImage];
            }
            
        }
        
        
        [label mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(payBtn.mas_bottom).offset(30 * WIDTHRADIU);
            make.left.mas_equalTo(10 * WIDTHRADIU);
            make.width.mas_equalTo(ScreenWidth - 20 * WIDTHRADIU);
            //make.height.mas_equalTo(15);
            make.bottom.mas_equalTo(0);
        }];
        //_scrollView.contentSize = CGSizeMake(ScreenWidth, topView.maxY + 10);
    }
    return _scrollView;
}

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