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

#import "SaveCardMoftifyController.h"
#import "SaveCardMotifyView.h"
#import "KBankListModel.h"

#import "BankPresentView.h"
#import "SaveBankModel.h"
#import "SMSVerificationController.h"

@interface SaveCardMoftifyController ()<UITextFieldDelegate>
{
    BOOL isOk;
}

@property (nonatomic, strong)SaveCardMotifyView* topView;

@property (nonatomic, assign)BOOL textIsEmpty;

@end

@implementation SaveCardMoftifyController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:self.topView];
    //初始化
    self.textIsEmpty = YES;
    [self setButtonState];
    
    [self.topView.tf_card addTarget:self action:@selector(textFieldDidChange) forControlEvents:UIControlEventEditingChanged];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    UIBarButtonItem *bar = [[UIBarButtonItem alloc] initWithTitle:@"返回" style:0 target:nil action:nil];
    [self.navigationItem setBackBarButtonItem:bar];
    [_topView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.offset(0);
        make.left.mas_equalTo(0);
        make.width.mas_equalTo(ScreenWidth);
        make.height.mas_greaterThanOrEqualTo(70);
    }];
    
    [self.view layoutIfNeeded];
    
    [GTCountSDK trackCountEvent:@"save_wudangChangeBindCardCount" withArgs:nil];
}


#pragma mark - UITextFieldDelegate
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    NSString *text = [self.topView.tf_card text];
   //返回一个字符集,指定字符串中包含的字符
   NSCharacterSet *characterSet = [NSCharacterSet characterSetWithCharactersInString:@"0123456789\b"];
   //string = [string stringByReplacingOccurrencesOfString:@" " withString:@""];
   
   //invertedSet  除了characterSet中包含的字符都找出来
   if ([string rangeOfCharacterFromSet:[characterSet invertedSet]].location != NSNotFound) {
       return NO;
   }
   
   text = [text stringByReplacingCharactersInRange:range withString:string];
   text = [text stringByReplacingOccurrencesOfString:@" " withString:@""];
   
   //不能写nil
   NSString *newString = @"";
   while (text.length > 0) {
       //每4位截取/不够4位有多少截取多少
       NSString *subString = [text substringToIndex:MIN(text.length, 4)];
       newString = [newString stringByAppendingString:subString];
       //加空格
       if (subString.length == 4) {
           newString = [newString stringByAppendingString:@" "];
       }
       text = [text substringFromIndex:MIN(text.length, 4)];
   }
   newString = [newString stringByTrimmingCharactersInSet:[characterSet invertedSet]];
   //限制长度
   if (newString.length >= 24) {
       return NO;
   }
    
    return YES;
}


#pragma mark - textFieldDidChange
- (void)textFieldDidChange
{
    NSString*bankCode = [self.topView.tf_card.text stringByReplacingOccurrencesOfString:@" " withString:@""];
    if ([Tools IsBankCard:bankCode]) {
        self.textIsEmpty = NO;
    }else{
        self.textIsEmpty = YES;
    }
    [self setButtonState];
}


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


#pragma mark - event response
- (void)supportBtnClick:(UIButton *)sender
{
    NSString *plistPath = [[NSBundle mainBundle] pathForResource:@"BankList"ofType:@"plist"];
    NSArray*array = [NSArray arrayWithContentsOfFile:plistPath];
    NSMutableArray*bankArray = [NSMutableArray array];
    for (NSDictionary*dic in array) {
        SaveBankModel*model = [SaveBankModel new];
        model.bankName = dic[@"bankName"];
        model.bankImage = dic[@"bankImage"];
        model.orderMin = dic[@"orderMin"];
        model.dMin = dic[@"dMin"];
        [bankArray addObject:model];
    }

    [BankPresentView showBankListWithVC:self type:BankPresentViewTypeWuDang bankArray:bankArray block:nil];
}

- (void)nextBtnClick:(UIButton *)sender
{
    NSString* cardNo = [self.topView.tf_card.text stringByReplacingOccurrencesOfString:@" " withString:@""];
    if (![self isSupportCardWithCardNo:cardNo]) {
        [Tools showMessage:@"该银行卡号不支持!"];
        return;
    }
    [GTCountSDK trackCountEvent:@"save_wudangChangeBindCardSMSCount" withArgs:nil];
    SMSVerificationController*vc = [SMSVerificationController new];
    vc.title = @"更换绑定银行卡短信验证";
    vc.infoModel = self.infoModel;
    vc.nBindCard = cardNo;
    vc.type = SMSSendTypeTypeBindCardModify;
    [self.navigationController pushViewController:vc animated:YES];
}

#pragma mark - 判断是否是支持的银行卡号码
- (BOOL)isSupportCardWithCardNo:(NSString *)cardNo
{
    NSString*bankName = [self returnBankName:cardNo];
    NSString *plistPath = [[NSBundle mainBundle] pathForResource:@"BankList"ofType:@"plist"];
    NSArray*array = [NSArray arrayWithContentsOfFile:plistPath];
   
    BOOL success = NO;
    for (NSDictionary*dic in array) {
        NSString*name =  dic[@"bankName"];
        if ([name isEqualToString:bankName]) {
            success = YES;
            break;
        }
    }
    return success;
}

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


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

#pragma mark - getters and setters
- (SaveCardMotifyView *)topView
{
    if (!_topView) {
        _topView = [self getXiblWithClassName:@"SaveCardMotifyView"];
        _topView.tf_card.delegate = self;
        //银行卡匹配
        SaveAccountSubUserInfoModel*userInfo = self.infoModel.SUBPACKS[0];
        NSString*bankName = [self returnBankName:userInfo.SIGCARD];
        NSString*bankImage = nil;
        NSString*orderMin = nil;
        NSString*dMin = nil;
        _topView.lb_bankName.text = [NSString stringWithFormat:@"%@(%@)",bankName,[userInfo.SIGCARD substringFromIndex:userInfo.SIGCARD.length - 4]];
         
        NSString *plistPath = [[NSBundle mainBundle] pathForResource:@"BankList"ofType:@"plist"];
        NSArray*array = [NSArray arrayWithContentsOfFile:plistPath];
        
        BOOL success = NO;
        for (NSDictionary*dic in array) {
            NSString*name =  dic[@"bankName"];
            if ([name isEqualToString:bankName]) {
                success = YES;
                bankImage = dic[@"bankImage"];
                orderMin = dic[@"orderMin"];
                dMin = dic[@"dMin"];
                break;
            }
        }
        if (success) {
            _topView.bankIcon.image = [UIImage imageNamed:bankImage];
            _topView.lb_bankMessage.text =  [NSString stringWithFormat:@"单笔扣款限额%@万元,每日扣款限额%@万元",orderMin,dMin];
        }
        
        
        [_topView.supportBtn addTarget:self action:@selector(supportBtnClick:) forControlEvents:UIControlEventTouchUpInside];
        [_topView.nextBtn addTarget:self action:@selector(nextBtnClick:) forControlEvents:UIControlEventTouchUpInside];
        
    }
    return _topView;
}




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