//
//  GSignController.m
//  aiim
//
//  Created by gan on 2025/2/28.
//

#import "GSignController.h"
#import "config.h"
#import "UserNetApi.h"

@interface GSignController ()

@property (weak, nonatomic) IBOutlet UITextField *inputZH;
@property (weak, nonatomic) IBOutlet UITextField *inputMMA;
@property (weak, nonatomic) IBOutlet UITextField *inputMMB;
@property (weak, nonatomic) IBOutlet UITextField *inputYX;
@property (weak, nonatomic) IBOutlet UITextField *inputYZM;
@property (weak, nonatomic) IBOutlet UIButton *getyanzmBt;
@property (weak, nonatomic) IBOutlet UILabel *noteLb;
@property (weak, nonatomic) IBOutlet UIButton *zhuceBt;


@property (nonatomic) NSInteger count;
@property (strong, nonatomic) NSTimer *heatBeat;
@property (strong, nonatomic) NSString *youxiang;
@end

@implementation GSignController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self.navigationController setNavigationBarHidden:YES animated:NO];
    // 创建一个点击手势
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(dismissKeyboard)];
    // 将手势添加到主视图上
    [self.view addGestureRecognizer:tap];
    // 注册键盘显示通知
    [[NSNotificationCenter defaultCenter] addObserver:self
                                                selector:@selector(keyboardWillShow:)
                                                    name:UIKeyboardWillShowNotification object:nil];
    // 注册键盘隐藏通知
    [[NSNotificationCenter defaultCenter] addObserver:self
                                            selector:@selector(keyboardWillHide:)
                                                name:UIKeyboardWillHideNotification object:nil];
    [self initSubView];
}

-(void)dismissKeyboard{
    NSLog(@"dismissKeyboard");
    [self.view endEditing:YES];
}

-(void)initSubView{
    _inputZH.borderStyle=UITextBorderStyleNone;
    _inputZH.layer.borderWidth = 1.0f;
    _inputZH.layer.borderColor = globalColor(GCTypeGreen).CGColor; //globalColor(GCTypeGreen);
    _inputZH.layer.cornerRadius = 8.0f; // 可选，设置圆角
    _inputZH.backgroundColor = [UIColor clearColor];
    _inputZH.textColor=[UIColor whiteColor];
    NSString *note = NSLocalizedString(@"Sign-usernme-note", @"");
    NSMutableAttributedString *placeholder = [[NSMutableAttributedString alloc] initWithString:note attributes:@{NSForegroundColorAttributeName: [UIColor lightGrayColor]}];
    UIView *paddingView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 10, 0)];
    _inputZH.leftView = paddingView;
    _inputZH.leftViewMode = UITextFieldViewModeAlways;
    _inputZH.attributedPlaceholder = placeholder;
    
    _inputMMA.borderStyle=UITextBorderStyleNone;
    _inputMMA.layer.borderWidth = 1.0f;
    _inputMMA.layer.borderColor = globalColor(GCTypeGreen).CGColor; //globalColor(GCTypeGreen);
    _inputMMA.layer.cornerRadius = 8.0f; // 可选，设置圆角
    _inputMMA.backgroundColor = [UIColor clearColor];
    _inputMMA.textColor=[UIColor whiteColor];
    note = NSLocalizedString(@"Sign-passw-note", @"");
    NSMutableAttributedString *placeholder2 = [[NSMutableAttributedString alloc] initWithString:note attributes:@{NSForegroundColorAttributeName: [UIColor lightGrayColor]}];
    UIView *paddingView2 = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 10, 0)];
    _inputMMA.leftView = paddingView2;
    _inputMMA.leftViewMode = UITextFieldViewModeAlways;
    _inputMMA.attributedPlaceholder = placeholder2;
    
    _inputMMB.borderStyle=UITextBorderStyleNone;
    _inputMMB.layer.borderWidth = 1.0f;
    _inputMMB.layer.borderColor = globalColor(GCTypeGreen).CGColor; //globalColor(GCTypeGreen);
    _inputMMB.layer.cornerRadius = 8.0f; // 可选，设置圆角
    _inputMMB.backgroundColor = [UIColor clearColor];
    _inputMMB.textColor=[UIColor whiteColor];
    note = NSLocalizedString(@"Sign-passw-note", @"");
    NSMutableAttributedString *placeholder3 = [[NSMutableAttributedString alloc] initWithString:note attributes:@{NSForegroundColorAttributeName: [UIColor lightGrayColor]}];
    UIView *paddingView3 = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 10, 0)];
    _inputMMB.leftView = paddingView3;
    _inputMMB.leftViewMode = UITextFieldViewModeAlways;
    _inputMMB.attributedPlaceholder = placeholder3;
    
    
    _inputYX.borderStyle=UITextBorderStyleNone;
    _inputYX.layer.borderWidth = 1.0f;
    _inputYX.layer.borderColor = globalColor(GCTypeGreen).CGColor; //globalColor(GCTypeGreen);
    _inputYX.layer.cornerRadius = 8.0f; // 可选，设置圆角
    _inputYX.backgroundColor = [UIColor clearColor];
    _inputYX.textColor=[UIColor whiteColor];
    note = NSLocalizedString(@"Sign-qingshuryx", @"");
    NSMutableAttributedString *placeholder4 = [[NSMutableAttributedString alloc] initWithString:note attributes:@{NSForegroundColorAttributeName: [UIColor lightGrayColor]}];
    UIView *paddingView4 = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 10, 0)];
    _inputYX.leftView = paddingView4;
    _inputYX.leftViewMode = UITextFieldViewModeAlways;
    _inputYX.attributedPlaceholder = placeholder4;
    
    
    _inputYZM.borderStyle=UITextBorderStyleNone;
    _inputYZM.layer.borderWidth = 1.0f;
    _inputYZM.layer.borderColor = globalColor(GCTypeGreen).CGColor; //globalColor(GCTypeGreen);
    _inputYZM.layer.cornerRadius = 8.0f; // 可选，设置圆角
    _inputYZM.backgroundColor = [UIColor clearColor];
    _inputYZM.textColor=[UIColor whiteColor];
    note = NSLocalizedString(@"Sign-qingsryzm", @"");
    NSMutableAttributedString *placeholder5 = [[NSMutableAttributedString alloc] initWithString:note attributes:@{NSForegroundColorAttributeName: [UIColor lightGrayColor]}];
    UIView *paddingView5 = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 10, 0)];
    _inputYZM.leftView = paddingView5;
    _inputYZM.leftViewMode = UITextFieldViewModeAlways;
    _inputYZM.attributedPlaceholder = placeholder5;
    
    [_getyanzmBt setTitle:NSLocalizedString(@"Sign-huoquyzm", @"获取验证码") forState:UIControlStateNormal];
    _getyanzmBt.titleLabel.font = [UIFont systemFontOfSize: 15.0];
    [_getyanzmBt setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [_getyanzmBt setBackgroundColor:globalColor(GCTypeGreen)];
    _getyanzmBt.layer.cornerRadius = 16;
    _getyanzmBt.layer.masksToBounds = YES; // 防止子视图超出圆角边界
    
    _noteLb.numberOfLines=3;
    _noteLb.font = [UIFont systemFontOfSize:14.0f];
    _noteLb.textColor = globalColor(GCTypeDark3);
    _noteLb.text =NSLocalizedString(@"Sign-yanzhengmts", @"");
    
    [_zhuceBt setTitle:NSLocalizedString(@"Sign-zhuce", @"注册") forState:UIControlStateNormal];
    _zhuceBt.titleLabel.font = [UIFont systemFontOfSize: 19.0];
    [_zhuceBt setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [_zhuceBt setBackgroundColor:globalColor(GCTypeGreen)];
    _zhuceBt.layer.cornerRadius = 27;
    _zhuceBt.layer.masksToBounds = YES; // 防止子视图超出圆角边界

    _count = 0;
    [self startHeartbeat];
}

-(void)dealloc{
    [self destoryHeartbeat];
}

- (void)keyboardWillShow:(NSNotification *)notification {
    CGFloat moveF = 0;
    
    if(_inputMMB.isFirstResponder){
        moveF = -100.0f;
    }
    if(_inputYX.isFirstResponder){
        moveF = -150.0f;
    }
    if(_inputYZM.isFirstResponder){
        moveF = -250.0f;
    }
    
    CGRect frame = self.view.frame;
    NSLog(@"frame.origin.y:%f",frame.origin.y);
    frame.origin.y=moveF;
    NSDictionary *userInfo = [notification userInfo];
    double duration = [[userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey] doubleValue];
    UIViewAnimationCurve curve = [[userInfo objectForKey:UIKeyboardAnimationCurveUserInfoKey] integerValue];
    [UIView animateWithDuration:duration
                         delay:0.0
                       options:(curve << 16)
                    animations:^{
                        self.view.frame = frame;;
                    } completion:nil];
    
   
}
 
- (void)keyboardWillHide:(NSNotification *)notification{
    CGRect frame = self.view.frame;
    frame.origin.y=0;
    self.view.frame = frame;
}

- (IBAction)gotoBack:(id)sender {
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (IBAction)getyanzmAct:(id)sender {
    if(_count==0){
        
        _youxiang =_inputYX.text;
        
        NSString *emailRegex = @"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,64}|[\\p{L}0-9._%+-]+@[\\p{L}0-9.-]+\\.[\\p{L}]{2,}";
        //NSString *emailRegex = @"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,64}";
        NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex];
        BOOL isValid = [emailTest evaluateWithObject:_youxiang];
        if (isValid) {
            _count = 60;
            [self sendYanzhengma];
        } else {
            NSLog(@"Email is invalid");
        }
    }
}

- (IBAction)zbuceAct:(id)sender {
    
    if([_inputYX.text isEqualToString:_youxiang]){
        if([_inputMMA.text isEqualToString:_inputMMB.text]){
            if(_inputZH.text.length>3&&_inputMMA.text.length>3&&_inputYZM.text.length>3){
                
                NSString *emailRegex =  @"^[a-zA-Z0-9]+$";
                NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex];
                BOOL isValid = [emailTest evaluateWithObject:_inputZH.text];
                if(isValid){
                    [self updateSign];
                }
                else{
                    [MBProgressHUD showWithText:@"帳號只能包含數位字母"];
                }
            }
            else{//所有项目为必填，且不小于4个字符
                
            }
        }
        else{//密码输入不一致
            
        }
    }
    else{//邮箱不是获取验证码的邮箱
        
    }
    
    
}


//定时服务
- (void)startHeartbeat {
    self.heatBeat = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(heartbeatAction) userInfo:nil repeats:YES];
    [self.heatBeat setFireDate:[NSDate distantPast]];
    [[NSRunLoop currentRunLoop] addTimer:_heatBeat forMode:NSRunLoopCommonModes];
}


//销毁定时
- (void)destoryHeartbeat{
    [self.heatBeat invalidate];
    self.heatBeat = nil;
}

-(void)heartbeatAction{
    if(_count>0){
        NSString *note = [NSString stringWithFormat:@"%@(%ld)",NSLocalizedString(@"Sign-wangjimm", @"验证码"),(long)_count];
        [_getyanzmBt setTitle:note forState:UIControlStateNormal];
        _count=_count-1;
    }
    else{
        [_getyanzmBt setTitle:NSLocalizedString(@"Sign-huoquyzm", @"获取验证码") forState:UIControlStateNormal];
    }
}

#pragma mark network

-(void)sendYanzhengma{
    NSLog(@"sendYanzhengma");
    [UserNetApi getEmailcode:_inputYX.text succ:^(int code, NSDictionary * res) {
        NSLog(@"res:%@",res);
    } fail:^(NSError * _Nonnull error) {
        NSLog(@"errer");
    }];
}

-(void)updateSign{
    
    NSDictionary *dic=@{
        @"host":@"",
        @"username":_inputZH.text,
        @"phonenumber":@"",
        @"email":_inputYX.text,
        @"password":_inputMMA.text,
        @"confirmPassword":_inputMMB.text,
        @"code":_inputYZM.text,
        @"uuid":@""
    };
    [UserNetApi sign:dic succ:^(int code, NSDictionary * res) {
        NSLog(@"res:%@",res);
        NSString *cd = res[@"code"];
        if(cd.intValue ==200){
            [self dismissViewControllerAnimated:YES completion:nil];
        }
        else{
            NSLog(@"注册账号失败！");
        }
        
    } fail:^(NSError * _Nonnull error) {
        NSLog(@"errer");
    }];
    
}


@end
