#import <UIKit/UIKit.h>

@interface BankCardFormat : UITextField

@end
#import "BankCardFormat.h"

@interface BankCardFormat ()<UITextFieldDelegate>
{
    NSString *previousTextFieldContent;
    
    UITextRange *previousSelection;
}
@end

@implementation BankCardFormat

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    
    if (self) {
        self.delegate = self;
        
        [self addTarget:self
         
       action          :@selector(reformatAsCardNumber:)
         
       forControlEvents:UIControlEventEditingChanged];
    }
    
    return self;
}

- (void)reformatAsCardNumber:(UITextField *)textField
{
    
    NSUInteger targetCursorPosition =[textField offsetFromPosition:textField.beginningOfDocument toPosition:textField.selectedTextRange.start];
    
    NSString *cardNumberWithoutSpaces =[self removeNonDigits:textField.text andPreserveCursorPosition:&targetCursorPosition];
    
    if ([cardNumberWithoutSpaces length] > 19) {
        [textField setText:previousTextFieldContent];
        textField.selectedTextRange = previousSelection;
        return;
    }
    
    NSString *cardNumberWithSpaces =[self insertSpacesEveryFourDigitsIntoString:cardNumberWithoutSpaces
                                                      andPreserveCursorPosition:&targetCursorPosition];
    
    textField.text = cardNumberWithSpaces;
    UITextPosition *targetPosition =[textField positionFromPosition:[textField beginningOfDocument]offset:targetCursorPosition];
    
    [textField setSelectedTextRange:[textField textRangeFromPosition:targetPosition toPosition:targetPosition]];
}

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    previousTextFieldContent = textField.text;
    previousSelection = textField.selectedTextRange;
    
    return YES;
}
- (NSString *)removeNonDigits :(NSString *)string  andPreserveCursorPosition:(NSUInteger *)cursorPosition
{
    NSUInteger      originalCursorPosition = *cursorPosition;
    NSMutableString *digitsOnlyString = [NSMutableString new];
    
    for (NSUInteger i = 0; i < [string length]; i++) {
        unichar characterToAdd = [string characterAtIndex:i];
        
        if (isdigit(characterToAdd)) {
            NSString *stringToAdd =[NSString stringWithCharacters:&characterToAdd length:1];
            
            [digitsOnlyString appendString:stringToAdd];
        } else {
            if (i < originalCursorPosition) {
                (*cursorPosition)--;
            }
        }
    }
    
    return digitsOnlyString;
}
- (NSString *)insertSpacesEveryFourDigitsIntoString:(NSString *)string andPreserveCursorPosition :(NSUInteger *)cursorPosition
{
    NSMutableString *stringWithAddedSpaces = [NSMutableString new];
    NSUInteger      cursorPositionInSpacelessString = *cursorPosition;
    
    for (NSUInteger i = 0; i < [string length]; i++) {
        if ((i > 0) && ((i % 4) == 0)) {
            [stringWithAddedSpaces appendString:@" "];
            
            if (i < cursorPositionInSpacelessString) {
                (*cursorPosition)++;
            }
        }
        unichar     characterToAdd = [string characterAtIndex:i];
        NSString    *stringToAdd =
        [NSString stringWithCharacters:&characterToAdd length:1];
        
        [stringWithAddedSpaces appendString:stringToAdd];
    }
    
    return stringWithAddedSpaces;
}

@end
//银行卡号输入的时候要求四位一个空格
/*使用方法:
 
 BankCardFormat *bankCardNumber = [[BankCardFormat alloc]initWithFrame:CGRectMake(60, 122, 230, 50)];
 bankCardNumber.borderStyle = UITextBorderStyleLine;
 bankCardNumber.placeholder = @"请输入你的银行卡号";
 [self.view addSubview:bankCardNumber];
 
 */

//银行卡只显示后四位的做法
/*
 原始卡号
NSString * origincardNo = [_wedData  objectAtIndex:i][@"bankCardNo"];

NSString *firstCardNo = [origincardNo  substringToIndex:origincardNo.length-4];
DLog(@"")
//        后四位数字
NSString *lastfourCardno = [origincardNo  substringFromIndex:origincardNo.length - 4];
DLog(@"%@",lastfourCardno);


DLog("%lu",(unsigned long)origincardNo.length);

DLog("%lu",(unsigned long)firstCardNo.length);


NSString *replacecardNo = [firstCardNo  stringByReplacingOccurrencesOfString:firstCardNo withString:@"*****************************"];

DLog("%lu",(unsigned long)replacecardNo.length);


NSString *transform;

if (replacecardNo.length>firstCardNo.length) {
    
    transform = [replacecardNo  substringToIndex:firstCardNo.length];
}

DLog("%lu",(unsigned long)transform.length);

DLog("%@",replacecardNo);


NSString *cardNumberstr = [NSString stringWithFormat:@"%@%@",transform,lastfourCardno];

NSString *tmpStr = cardNumberstr;

DLog("%@",cardNumberstr);

DLog("%@",tmpStr);

int size = (int)tmpStr.length / 4;
NSMutableArray *tmpStrArr = [[NSMutableArray alloc] init];
for (int n = 0;n < size; n++)
{
    [tmpStrArr addObject:[tmpStr substringWithRange:NSMakeRange(n*4, 4)]];
}
[tmpStrArr addObject:[tmpStr substringWithRange:NSMakeRange(size*4, (tmpStr.length % 4))]];
tmpStr = [tmpStrArr componentsJoinedByString:@" "];

DLog("%lu",(unsigned long)tmpStr.length);
DLog("%@",tmpStr);

//tmpStr就是最终只显示后四位的的银行卡号
 */