//
//  RegisterViewController.m
//  Demo
//
//  Created by super on 2019/7/5.
//  Copyright © 2019 super. All rights reserved.
//

#import "RegisterViewController.h"
#import "XDTopHud.h"
#import <MagicalRecord/MagicalRecord.h>
#import "UserModel+CoreDataClass.h"
#import "UserModel+CoreDataProperties.h"
@interface RegisterViewController ()

@end

@implementation RegisterViewController

- (void)viewDidLoad {
    self.navigationController.navigationBarHidden = NO;
    self.navigationController.navigationBar.titleTextAttributes = @{NSForegroundColorAttributeName: [UIColor blackColor]};
    self.navigationController.navigationBar.barTintColor = [UIColor whiteColor];
    self.navigationController.navigationBar.backgroundColor = [UIColor whiteColor];
    UIButton* backBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [backBtn setImage:[UIImage imageNamed:@"back"] forState:UIControlStateNormal];
    [backBtn addTarget:self action:@selector(backAction) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem* backItem = [[UIBarButtonItem alloc] initWithCustomView:backBtn];
    self.navigationItem.leftBarButtonItem = backItem;
    self.edgesForExtendedLayout = UIRectEdgeBottom;
    self.title = @"注册";
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.textFieldName.layer.borderColor = [UIColor colorWithRed:271.0/255.0f green:248.0/255.0f blue:250.0f/255.0f alpha:1].CGColor;
    self.textFieldName.layer.borderWidth =1.0;
    self.textFieldName.layer.cornerRadius = 15;
    
    self.textFieldPassword.layer.borderColor = [UIColor colorWithRed:271.0/255.0f green:248.0/255.0f blue:250.0f/255.0f alpha:1].CGColor;
    self.textFieldPassword.layer.borderWidth =1.0;
    self.textFieldPassword.layer.cornerRadius = 15;
    
    self.textFieldPhone.layer.borderColor = [UIColor colorWithRed:271.0/255.0f green:248.0/255.0f blue:250.0f/255.0f alpha:1].CGColor;
    self.textFieldPhone.layer.borderWidth =1.0;
    self.textFieldPhone.layer.cornerRadius = 15;
    
    self.textFieldAge.layer.borderColor = [UIColor colorWithRed:271.0/255.0f green:248.0/255.0f blue:250.0f/255.0f alpha:1].CGColor;
    self.textFieldAge.layer.borderWidth =1.0;
    self.textFieldAge.layer.cornerRadius = 15;
    
    self.textFieldSex.layer.borderColor = [UIColor colorWithRed:271.0/255.0f green:248.0/255.0f blue:250.0f/255.0f alpha:1].CGColor;
    self.textFieldSex.layer.borderWidth =1.0;
    self.textFieldSex.layer.cornerRadius = 15;
    
    self.textFieldHeight.layer.borderColor = [UIColor colorWithRed:271.0/255.0f green:248.0/255.0f blue:250.0f/255.0f alpha:1].CGColor;
    self.textFieldHeight.layer.borderWidth =1.0;
    self.textFieldHeight.layer.cornerRadius = 15;
    
    self.textFieldWeight.layer.borderColor = [UIColor colorWithRed:271.0/255.0f green:248.0/255.0f blue:250.0f/255.0f alpha:1].CGColor;
    self.textFieldWeight.layer.borderWidth =1.0;
    self.textFieldWeight.layer.cornerRadius = 15;
    
    self.btnRegist.layer.cornerRadius = 25;
}

-(void)backAction
{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    NSArray * arr =  self.view.subviews;
    for (int i = 0; i<arr.count; i++) {
        if ([arr[i] isKindOfClass:[UITextField class]]) {
            [arr[i] resignFirstResponder];
        }
    }
}
- (IBAction)registerAction:(id)sender {
    if(self.textFieldName.text.length <= 0 || self.textFieldName.text.length > 32 || ![self compareUser:self.textFieldName.text])
    {
        [XDTopHud showWarning:@"登录帐号规定为小于32 位，只能为数字、字母"];
        return;
    }
    
    NSArray *personsAgeEuqals3 = [UserModel MR_findByAttribute:@"userName" withValue:self.textFieldName.text];
    if(personsAgeEuqals3.count != 0)
    {
        [XDTopHud showWarning:@"该用户已存在"];
        return;
    }
    
    if(self.textFieldPassword.text.length < 6 || self.textFieldPassword.text.length > 16 || ![self comparePassWordLegal:self.textFieldPassword.text] )
    {
        [XDTopHud showWarning:@"密码规定为6-16位字母+数字"];
        return;
    }
    
    if(self.textFieldPhone.text.length > 0 )
    {
        if(![self comparePhone:self.textFieldPhone.text])
        {
            [XDTopHud showWarning:@"请输入正确的手机号"];
            return;
        }
    }
    
    UserModel * model = [UserModel MR_createEntity];
    model.userName = self.textFieldName.text;
    model.userAge = self.textFieldAge.text;
    model.userSex = self.textFieldSex.text;
    model.userPassword =self.textFieldPassword.text;
    model.userPhone = self.textFieldPhone.text;
    model.userWeight = self.textFieldWeight.text;
    model.userHeight = self.textFieldHeight.text;
    
    [[NSManagedObjectContext MR_defaultContext] MR_saveToPersistentStoreWithCompletion:^(BOOL success, NSError *error) {
        NSLog(@"SUCCESS: %d, with ERROR: %@", success, error);
        if(success){
            [XDTopHud showSuccess:@"注册成功"];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 3.0*NSEC_PER_SEC), dispatch_get_main_queue(), ^{
                [self.navigationController popViewControllerAnimated:YES];
            });
        }
    }];
    
    NSArray* users = [UserModel MR_findByAttribute:@"userName" withValue:@"ls"];
    UserModel* user = users.firstObject;
    NSLog(@"%@",user.userPassword);
}


//验证手机号
-(BOOL)comparePhone:(NSString*)phone
{
    NSString *pattern = @"^1+[345789]+\\d{9}";
    NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", pattern];
    BOOL isMatch = [pred evaluateWithObject:phone];
    return isMatch;
}

//验证字母或数字
-(BOOL)compareUser:(NSString *)str{
    if (str.length < 1) {
        return NO;
    }

    if([self isNineKeyChinese:[str substringFromIndex:str.length - 1]])
    {
        return YES;
    }
    
    
    NSString * regex = @"[A-Za-z0-9]*";
    NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex];
    BOOL isMatch = [pred evaluateWithObject:str];
    return isMatch;
}
-(BOOL)isNineKeyChinese:(NSString *)str
{
    NSString *other = @"➋➌➍➎➏➐➑➒";
    unsigned long len=str.length;
    for(int i=0;i<len;i++)
    {
        if(!([other rangeOfString:str].location != NSNotFound))
            return NO;
    }
    return YES;
}

//验证字母+数字
-(BOOL)comparePassWordLegal:(NSString *)pass{
    
    BOOL result = false;
    NSString * regex = @"^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,16}$";
    NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex];
    result = [pred evaluateWithObject:pass];
    return result;
    
}
@end
