//
//  AuthCodeInputView.m
//  隐私保护
//
//  Created by xd h on 2023/11/7.
//

#import "AuthCodeInputView.h"
#import "AuthCodeTextField.h"
#import "connectDeviceManager.h"
#import "RSATool.h"

@interface AuthCodeInputView () <UITextFieldDelegate,AuthCodeDeleteDelegate>

@property (nonatomic,strong) NSString *phone;

@property (nonatomic,strong) UIView *backGround;

@property (nonatomic,strong) NSMutableArray *tfArr;

@property (nonatomic,strong) NSString *codeStr;

@end

@implementation AuthCodeInputView

-(instancetype)initWithFrame:(CGRect)frame{
    if(self = [super initWithFrame:frame])
    {
        //_phone = phone;
        [self createSubviews];
        [self sendSMSMessage];
        [[NSNotificationCenter defaultCenter] addObserver:self
                                                     selector:@selector(keyboardWillShow:)
                                                         name:UIKeyboardWillShowNotification
                                                       object:nil];
    }
    return self;
}

-(void)dealloc{
    [[NSNotificationCenter defaultCenter]removeObserver:self];
}

// 发送短信验证码
-(void)sendSMSMessage
{
}

-(void)createSubviews
{
    _backGround = [[UIView alloc]init];
    _backGround.backgroundColor = HWF5F7FAColor;
    [self addSubview:_backGround];
//    _backGround.layer.cornerRadius = 10;
//    _backGround.layer.masksToBounds = YES;
    
    [_backGround mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(0);
        make.right.mas_equalTo(0);
        make.top.mas_equalTo(0);
        make.bottom.mas_equalTo(0);
    }];
   
   
    
    UILabel *titleLab = [[UILabel alloc]init];
    titleLab.text = @"请输入8位密钥";
    titleLab.textColor = [UIColor hwColor:@"#333333" alpha:1.0];
    titleLab.font = [UIFont systemFontOfSize:16];
    titleLab.textAlignment = NSTextAlignmentCenter;
    [_backGround addSubview:titleLab];
    [titleLab sizeToFit];
    [titleLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(0);
        make.right.mas_equalTo(0);
        make.top.mas_equalTo(40);
        make.height.mas_equalTo(30);
    }];
    
    
    
    self.tfArr = [NSMutableArray array];
    // 八个输入框
    NSInteger numOfInputs = 8;
    CGFloat padding = 8;
    CGFloat leftRightPadding = 15;
    CGFloat allPadding = leftRightPadding *2 + (numOfInputs - 1)*padding;
    CGFloat width = (SCREEN_W - allPadding)/8.0;
    for (int i = 1 ; i <= numOfInputs; i ++) {
        AuthCodeTextField *textF = [[AuthCodeTextField alloc]init];
        textF.tag = i;
        textF.auth_delegate = self;
        textF.delegate = self;
        [_backGround addSubview:textF];
        [self.tfArr addObject:textF];
        if(i == 1){
            [textF becomeFirstResponder];
        }
//        CGFloat offset = 0;
//        if(i <= 3){
//            offset = -width*(3-i) - padding *(3-i) - padding/2 - width/2;
//        }else{
//            offset =  width*(i-4) + padding *(i-4) + padding/2 + width/2;
//        }
        [textF mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(titleLab.mas_bottom).offset(25);
            make.width.mas_equalTo(width);
            make.height.mas_equalTo(85/2);
            //make.centerX.mas_equalTo(offset);
            make.left.mas_equalTo(leftRightPadding + (padding+width)*(i-1));
        }];
    }
}

#pragma mark  UITextFieldDelegate
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
// 获取短信中提取的验证码，自动输入到输入框中
    if(string.length > 1){
        for (int i = 0 ; i < self.tfArr.count; i++) {
            AuthCodeTextField *tf = self.tfArr[i];
            tf.text = [string substringWithRange:NSMakeRange(i, 1)];
        }
        return NO;
    }
    NSInteger nextTag = textField.tag + 1;
    UITextField *nextTextField = [self viewWithTag:nextTag];
    if(string.length > 0){
        textField.text = string;
        if (nextTextField && [nextTextField.text isEqualToString:@""]) {
            [nextTextField becomeFirstResponder];
        }
        else
        {
            self.codeStr = @"";
            for (AuthCodeTextField *tf in self.tfArr) {
                self.codeStr = [self.codeStr stringByAppendingString:tf.text];
            }
            HLog(@"输入的验证码:%@",self.codeStr);
            
            if(self.codeStr.length == 8){
                [self checkAuthcode];
            }
        }
        return NO;
    }
    else
    {
        return YES;
    }
}
// 调用接口验证验证码正确性
-(void)checkAuthcode
{
    NSString *snStr = [connectDeviceManager shareInstance].DeviceThirdIdMod.data.sn;
    NSString *secretkey  = [RSATool sha256_8:snStr];
    
    NSString*inputCodeStr = [self.codeStr uppercaseString];
    
    if([secretkey isEqualToString:inputCodeStr]){
        if(_authSuccess){
            _authSuccess(YES);
        }
    }
    else{
       NSString* curTipStr = NSLocalizedString(@"logo_input_pwd_fail",nil);
       [[iToast makeText:curTipStr] show];
    }
}

-(void)closeAuthCodeInputView{
    [self removeFromSuperview];
}

#pragma mark  AuthCodeDeleteDelegate 删除输入的值
-(void)authCodeTextFieldDeleteBackward:(AuthCodeTextField *)textField
{   self.codeStr = @"";
    NSInteger lastTag = textField.tag - 1;
    AuthCodeTextField *lastTextField = [self viewWithTag:lastTag];
    [lastTextField becomeFirstResponder];
}

#pragma mark  NSNotificationCenter
-(void)keyboardWillShow:(NSNotification *)notify
{
//    NSDictionary *userInfo = [notify userInfo];
//    NSValue *aValue = [userInfo objectForKey:UIKeyboardFrameEndUserInfoKey];
//    CGRect keyboardRect = [aValue CGRectValue];
//    //height 就是键盘的高度
//    int height = keyboardRect.size.height;
//    [_backGround mas_remakeConstraints:^(MASConstraintMaker *make) {
//        make.left.mas_equalTo(0);
//        make.right.mas_equalTo(0);
//        make.height.mas_equalTo(320);
//        make.bottom.mas_equalTo(-height+10);
//    }];
}

@end

