//
//  registerViewController.m
//  gaotingshan
//
//  Created by MacBook Dq01 on 16/3/18.
//  Copyright © 2016年 Mac Book DQ02. All rights reserved.
//

#import "registerViewController.h"
#import "LoginViewController.h"
#import "AgreementViewController.h"
#import "AFNetworking.h"
#import "MyMD5.h"

#define kMargin 10
#define kScreenwidth [UIScreen mainScreen].bounds.size.width
#define kScreenheight [UIScreen mainScreen].bounds.size.height
#define kheight kScreenheight*0.065
#define knavBarHeight self.navigationController.navigationBar.frame.size.height  //获取导航栏的高度
#define isBtnWH kScreenheight*0.035

@interface registerViewController () <UITextFieldDelegate> {
    //为登录状态下（以下4个字段）
    NSString *type;
    NSString *key;
    NSString *time;
    NSString *sign;
    //注册字段4个(登录类型，用户名，密码，昵称)
    NSString *login_type;
    //获取验证码字段(手机号码)
    UITextField *phoneTF; //输入手机号
    UITextField *nickNameTF; //昵称
    UITextField *inputIdentifyingCode; //输入验证码
    UITextField *inputPWTF; //输入密码
    UITextField *confirmPWTF; //确认密码
    UIButton *getIdentifyingCodeBtn; //获取验证码
    UIButton *isBtn; //是否同意智慧登山服务协议
    UIButton *registerBtn; //注册按钮
    UILabel *agreementLabel; //我已同意并阅读
    
    //接收验证码
    NSString *receiveIdentifyingCode;
    
}

@property (nonatomic, strong) UIButton *agreementBtn;

@property (nonatomic, assign) NSInteger second;
@property (nonatomic, assign) NSTimer *timer;

@property (nonatomic, strong) UILabel *isRegisterWarninglabel;

@property (nonatomic, strong) UILabel *isObserveAgreement;

//警示框
@property (nonatomic, strong) UILabel *phoneTFWarningLab;
@property (nonatomic, strong) UILabel *nickTFWarningLab;
@property (nonatomic, strong) UILabel *indentifyCodeTFWarningLab;
@property (nonatomic, strong) UILabel *pwdTFWarningLab;
@property (nonatomic, strong) UILabel *confirPwdTFWarningLab;

//用于记录输入框的输入是否合理，合规则
@property (nonatomic, assign) BOOL phoneLegal;//手机号输入框是否合法
@property (nonatomic, assign) BOOL nickLegal;//昵称
@property (nonatomic, assign) BOOL indetifyCodeLegal;//验证码框
@property (nonatomic, assign) BOOL pwdLegal;//密码
@property (nonatomic, assign) BOOL confirPwdLegal;//密码确认

@end

@implementation registerViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    _second = 60;
    
    self.view.backgroundColor = [UIColor colorWithRed:241/255. green:241/255. blue:241/255. alpha:0.99];
    //设置导航栏标题
    self.navigationItem.title = @"注册";
    
    //    //改变导航栏的渲染颜色
    //    [self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:@"nav_bg"] forBarMetrics:(UIBarMetricsDefault)];
    //    //改变字体颜色
    //    NSMutableDictionary *textAttrs = [NSMutableDictionary dictionary];
    //    textAttrs[NSForegroundColorAttributeName] = [UIColor whiteColor];
    //    self.navigationController.navigationBar.titleTextAttributes = textAttrs;
    
    [Manager setNavi:self.navigationController.navigationBar];
    
    
    //用push推过来后，可以重新设定导航栏左边的按钮  zuoback backIsClicked
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"nav_back.png"] landscapeImagePhone:nil style:UIBarButtonItemStylePlain target:self action:@selector(backIsClicked)];
    self.navigationItem.leftBarButtonItem.tintColor = [UIColor whiteColor];
    
    //设置导航栏右边的取消按钮，作用取消用户的所有操作
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"重置" style:(UIBarButtonItemStyleDone) target:self action:@selector(cancelIsClicked)];
    //改变图片的渲染颜色
    self.navigationItem.rightBarButtonItem.tintColor = [UIColor whiteColor];
    
#pragma － UI布局（UITextField包括输入手机号，昵称，输入验证码，获取验证码，输入密码，确认密码，UIButton包括我已阅读并同意。 确定）
    phoneTF = [[UITextField alloc] initWithFrame:CGRectMake(kMargin, 2*kMargin, kScreenwidth - 2*kMargin, kheight)];
    phoneTF.tag = 100;
    phoneTF.borderStyle = UITextBorderStyleRoundedRect;
    [phoneTF addTarget:self action:@selector(judgePhoneRegister) forControlEvents:(UIControlEventEditingDidEnd)];
    phoneTF.delegate = self;
    phoneTF.backgroundColor = [UIColor whiteColor];
    phoneTF.placeholder = @"请输入手机号";
    phoneTF.keyboardType = UIKeyboardTypePhonePad;
    [self.view addSubview:phoneTF];
    
    nickNameTF = [[UITextField alloc] initWithFrame:CGRectMake(kMargin, CGRectGetMaxY(phoneTF.frame) + 2*kMargin, kScreenwidth - 2*kMargin, kheight)];
    nickNameTF.delegate = self;
    nickNameTF.tag = 101;
    nickNameTF.borderStyle =UITextBorderStyleRoundedRect;
    [nickNameTF addTarget:self action:@selector(nicknameTFIsClicked) forControlEvents:(UIControlEventEditingChanged)];
    nickNameTF.backgroundColor = [UIColor whiteColor];
    nickNameTF.placeholder = @"昵称";
    [self.view addSubview:nickNameTF];
    
    //输入验证码文本框
    inputIdentifyingCode = [[UITextField alloc] initWithFrame:CGRectMake(kMargin, CGRectGetMaxY(nickNameTF.frame) + 2*kMargin, ((nickNameTF.frame.size.width - kMargin)/3)*2, kheight)];
    inputIdentifyingCode.tag = 102;
    inputIdentifyingCode.borderStyle = UITextBorderStyleRoundedRect;
    inputIdentifyingCode.placeholder = @"输入验证码";
    inputIdentifyingCode.keyboardType = UIKeyboardTypePhonePad;
    [inputIdentifyingCode addTarget:self action:@selector(inputIdentifyingCodeIsClicked) forControlEvents:(UIControlEventEditingChanged)];
    inputIdentifyingCode.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:inputIdentifyingCode];
    
    //获取验证码按钮
    getIdentifyingCodeBtn = [UIButton buttonWithType:UIButtonTypeSystem];
    getIdentifyingCodeBtn.frame = CGRectMake(CGRectGetMaxX(inputIdentifyingCode.frame) + kMargin, CGRectGetMaxY(nickNameTF.frame) + 2*kMargin, (nickNameTF.frame.size.width - kMargin)/3, kheight);
    
    getIdentifyingCodeBtn.backgroundColor = [UIColor whiteColor];
    [getIdentifyingCodeBtn setTitle:@"获取验证码" forState:UIControlStateNormal];
    [getIdentifyingCodeBtn setTitleColor:[UIColor colorWithRed:34.0/255 green:205.0/255 blue:119.0/255 alpha:1] forState:(UIControlStateNormal)];
    getIdentifyingCodeBtn.layer.cornerRadius = 5;
    getIdentifyingCodeBtn.layer.masksToBounds = YES;
    [getIdentifyingCodeBtn addTarget:self action:@selector(getIdentifyingCodeBtnIsClicked:) forControlEvents:(UIControlEventTouchUpInside)];
    [self.view addSubview:getIdentifyingCodeBtn];
    
    //输入密码
    inputPWTF = [[UITextField alloc] initWithFrame:CGRectMake(kMargin, CGRectGetMaxY(inputIdentifyingCode.frame) + 2*kMargin, kScreenwidth - 2*kMargin, kheight)];
    inputPWTF.borderStyle = UITextBorderStyleRoundedRect;
    inputPWTF.placeholder = @"输入密码";
    inputPWTF.delegate = self;
    inputPWTF.tag = 103;
    inputPWTF.secureTextEntry = YES;
    [inputPWTF addTarget:self action:@selector(inputPWTFeditingIsClicked) forControlEvents:(UIControlEventEditingChanged)];
    [inputPWTF addTarget:self action:@selector(inputPWTFEditEndIsClicked) forControlEvents:(UIControlEventEditingDidEnd)];
    inputPWTF.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:inputPWTF];
    
    //确认密码
    confirmPWTF = [[UITextField alloc] initWithFrame:CGRectMake(kMargin, CGRectGetMaxY(inputPWTF.frame) + 2*kMargin, kScreenwidth - 2*kMargin, kheight)];
    confirmPWTF.borderStyle = UITextBorderStyleRoundedRect;
    confirmPWTF.placeholder = @"确认密码";
    confirmPWTF.tag = 104;
    confirmPWTF.delegate = self;
    confirmPWTF.secureTextEntry = YES;
    confirmPWTF.backgroundColor = [UIColor whiteColor];
    [confirmPWTF addTarget:self action:@selector(confirmPWDTFEditingEnd) forControlEvents:(UIControlEventEditingDidEnd)];
    [self.view addSubview:confirmPWTF];
    
    //是否同意登山按钮协议
    isBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    isBtn.frame = CGRectMake(2.5*kMargin, CGRectGetMaxY(confirmPWTF.frame) + 3*kMargin, isBtnWH, isBtnWH);
    [isBtn setImage:[UIImage imageNamed:@"fangkuanggouxuan.png"] forState:UIControlStateNormal];
    [isBtn setImage:[UIImage imageNamed:@"fangkuang.png"] forState:(UIControlStateSelected)];
    [isBtn addTarget:self action:@selector(register_isBtnIsClicked:) forControlEvents:(UIControlEventTouchUpInside)];
    isBtn.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:isBtn];
    
    agreementLabel = [[UILabel alloc] initWithFrame:CGRectMake(CGRectGetMaxX(isBtn.frame) + kMargin, CGRectGetMaxY(confirmPWTF.frame) + 3*kMargin, (kScreenwidth - CGRectGetMaxX(isBtn.frame) - 2*kMargin)/2., isBtnWH)];
    agreementLabel.textAlignment = NSTextAlignmentLeft;  //文本对齐方式
    agreementLabel.font = [UIFont systemFontOfSize:14];
    //高度固定并且不换行，根据字的多少计算label的宽度
    NSString *str = @"我已阅读并同意";
    NSDictionary *attrs = @{NSFontAttributeName : agreementLabel.font};
    CGRect size1= [str boundingRectWithSize:CGSizeMake(MAXFLOAT, isBtnWH) options:NSStringDrawingUsesLineFragmentOrigin attributes:attrs context:nil];
    NSLog(@"str.width = %f",size1.size.width);
    //方法废弃了
    //  CGSize size = [str sizeWithFont:agreementLabel.font constrainedToSize:CGSizeMake(MAXFLOAT, isBtnWH)];
    
    agreementLabel.text = str;
    agreementLabel.backgroundColor = [UIColor colorWithRed:241/255. green:241/255. blue:241/255. alpha:0.99];
    agreementLabel.frame = CGRectMake(CGRectGetMaxX(isBtn.frame) + kMargin, CGRectGetMaxY(confirmPWTF.frame) + 3*kMargin, size1.size.width, isBtnWH);
    [self.view addSubview:agreementLabel];
    
    
    _agreementBtn = [[UIButton alloc] initWithFrame:CGRectMake(CGRectGetMaxX(agreementLabel.frame), CGRectGetMaxY(confirmPWTF.frame) + 3*kMargin, kScreenwidth - CGRectGetMaxX(agreementLabel.frame) - 2*kMargin, isBtnWH)];
    [_agreementBtn setTitle:@"《智慧登山服务协议》" forState:(UIControlStateNormal)];
    [_agreementBtn setTitleColor:[UIColor blueColor] forState:(UIControlStateNormal)];
    _agreementBtn.titleLabel.font = [UIFont systemFontOfSize:14];
    _agreementBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
    [_agreementBtn addTarget:self action:@selector(agreementBtnIsClicked) forControlEvents:(UIControlEventTouchUpInside)];
    _agreementBtn.backgroundColor = [UIColor colorWithRed:241/255. green:241/255. blue:241/255. alpha:0.99];
    [self.view addSubview:_agreementBtn];
    
    //注册按钮。
    registerBtn = [UIButton buttonWithType:UIButtonTypeSystem];
    registerBtn.frame = CGRectMake(kMargin, CGRectGetMaxY(isBtn.frame) + 2*kMargin, kScreenwidth - 2*kMargin, kheight);
    [registerBtn setTitle:@"注册" forState:UIControlStateNormal];
    [registerBtn setTitleColor:[UIColor whiteColor] forState:(UIControlStateNormal)];
    registerBtn.titleLabel.font = [UIFont systemFontOfSize:16];
    [registerBtn addTarget:self action:@selector(registerBtnIsClicked:) forControlEvents:(UIControlEventTouchUpInside)];
    registerBtn.backgroundColor = [UIColor blackColor];
    [self.view addSubview:registerBtn];
    
    [self setWarningLabels];
}

#pragma mark 输入框下面的警示标签
-(void)setWarningLabels
{
    //给出提示框,电话号码输入框提示
    _phoneTFWarningLab = [[UILabel alloc] initWithFrame:CGRectMake(kMargin, CGRectGetMaxY(phoneTF.frame), kScreenwidth - 2*kMargin, 2*kMargin)];
    _phoneTFWarningLab.textAlignment = NSTextAlignmentRight;
    _phoneTFWarningLab.textColor = [UIColor redColor];
    _phoneTFWarningLab.font = [UIFont systemFontOfSize:12];
    [self.view addSubview:_phoneTFWarningLab];
    
    //昵称输入框警示
    _nickTFWarningLab = [[UILabel alloc] initWithFrame:CGRectMake(kMargin, CGRectGetMaxY(nickNameTF.frame), kScreenwidth - 2*kMargin, 2*kMargin)];
    _nickTFWarningLab.textAlignment = NSTextAlignmentRight;
    _nickTFWarningLab.textColor = [UIColor redColor];
    _nickTFWarningLab.font = [UIFont systemFontOfSize:12];
    [self.view addSubview:_nickTFWarningLab];
    
    //验证码输入框警示
    _indentifyCodeTFWarningLab = [[UILabel alloc] initWithFrame:CGRectMake(kMargin, CGRectGetMaxY(getIdentifyingCodeBtn.frame), kScreenwidth - 2*kMargin, 2*kMargin)];
    _indentifyCodeTFWarningLab.textAlignment = NSTextAlignmentRight;
    _indentifyCodeTFWarningLab.textColor = [UIColor redColor];
    _indentifyCodeTFWarningLab.font = [UIFont systemFontOfSize:12];
    [self.view addSubview:_indentifyCodeTFWarningLab];
    
    //密码输入框警示
    _pwdTFWarningLab = [[UILabel alloc] initWithFrame:CGRectMake(kMargin, CGRectGetMaxY(inputPWTF.frame), kScreenwidth - 2*kMargin, 2*kMargin)];
    _pwdTFWarningLab.textAlignment = NSTextAlignmentRight;
    _pwdTFWarningLab.textColor = [UIColor redColor];
    _pwdTFWarningLab.font = [UIFont systemFontOfSize:12];
    [self.view addSubview:_pwdTFWarningLab];
    
    //密码确认输入框警示
    _confirPwdTFWarningLab = [[UILabel alloc] initWithFrame:CGRectMake(kMargin, CGRectGetMaxY(confirmPWTF.frame), kScreenwidth - 2*kMargin, 2*kMargin)];
    _confirPwdTFWarningLab.textAlignment = NSTextAlignmentRight;
    _confirPwdTFWarningLab.textColor = [UIColor redColor];
    _confirPwdTFWarningLab.font = [UIFont systemFontOfSize:12];
    [self.view addSubview:_confirPwdTFWarningLab];
    
}


#pragma mark - 当文本框编辑结束后，监控phoneTF事件，用于判断该手机号是否注册过以及是否合法
- (void)judgePhoneRegister {
    _isClickIdentify = NO;
    [self verifyPhoneWhetherLegal];
}

#pragma mark --验证手机号码合法性的函数
-(void)verifyPhoneWhetherLegal
{
    _phoneTFWarningLab.text = @"";
    if (phoneTF.text.length < 11 || phoneTF.text.length > 11) {
        _phoneLegal = NO;//输入不合法
        //给出提示框
        _phoneTFWarningLab.text = @"手机号码不能为空且为11位";
        return;
    }
    
    //判断号码是否合法
    BOOL isCorrectPhone =[Manager checkTelNumber:phoneTF.text];
    if (isCorrectPhone == NO) {
        _phoneLegal = NO;
        _phoneTFWarningLab.text = @"无效手机号码";
        return;
    }
    
    NSDictionary *dicx;
    type = @"Ios";
    key = @".5Xf_01KXd352s177Jx3wxXc074poII";
    time = @"yyyyMMddHHmmss";
    //sign 需要MD5加密方式. 传入字符串（time+type+key），需要用到字符串拼接。
    NSString *str = [[NSString alloc] initWithFormat:@"%@%@%@", time, type, key];
    sign = [MyMD5 md5:str];
    dicx = @{@"type" : type, @"key" : key, @"time" : time, @"sign" : sign, @"phone" : phoneTF.text};
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    NSString *postStr = [NSString stringWithFormat:@"%@/terminal/phoneapi",localRequestUrl];
    
    [manager POST:postStr parameters:dicx constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"%@", responseObject[@"code"]);
        //4025表示已经注册过  4026表示未注册过   4021表示手机号码异常
        if ([responseObject[@"code"] isEqualToString:@"4025"]) {
            
            _phoneLegal = NO;
            _phoneTFWarningLab.text = @"该号码已经注册过";
            [self.view addSubview:_phoneTFWarningLab];
            return;
        }else if ([responseObject[@"code"] isEqualToString:@"4021"])
        {
            _phoneLegal = NO;
            _phoneTFWarningLab.text = @"该手机号码异常";
            [self.view addSubview:_phoneTFWarningLab];
            return;
        }
        else if ([responseObject[@"code"] isEqualToString:@"4026"])
        {
            _phoneLegal = YES;
            _phoneTFWarningLab.text = @"";
            if (self.isClickIdentify) {
                //表示按了获取验证码按钮，号码已注册，表示可以进行验证码请求
                [self getIdentifyCode];
            }
            
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        //NSLog(@"不做处理");
    }];
    
}


#pragma mark - 实时监控nickTF文本框的输入事件，用于判断昵称是否合法
- (void)nicknameTFIsClicked {
    if (nickNameTF.text.length < 3 || nickNameTF.text.length > 10) {
        _nickTFWarningLab.text = @"昵称只能3到10个字符";
        _nickLegal = NO;
    }
    else
    {
        _nickLegal = YES;
        _nickTFWarningLab.text = @"";
    }
}

#pragma mark - 实时监控输入验证码文本框编辑事件的变化。
- (void)inputIdentifyingCodeIsClicked {
    if (inputIdentifyingCode.text.length == 0) {
        _indetifyCodeLegal = NO;
        _indentifyCodeTFWarningLab.text = @"验证码不能为空";
    }
    else
    {
        _indetifyCodeLegal = YES;
        _indentifyCodeTFWarningLab.text = @"";
    }
    
}

#pragma mark - 实时监控输入密码文本框编辑事件的变化
- (void)inputPWTFeditingIsClicked {
    if (inputPWTF.text.length == 0) {
        _pwdLegal = NO;
        _pwdTFWarningLab.text= @"密码不能为空";
    }
    else
    {
        _pwdLegal = YES;
        _pwdTFWarningLab.text = @"";
    }
}

- (void)inputPWTFEditEndIsClicked {
    if (inputPWTF.text.length < 6) {
        _pwdLegal = NO;
        _pwdTFWarningLab.text= @"密码长度必须大于6位";
    }
    else
    {
        _pwdLegal = YES;
        _pwdTFWarningLab.text= @"";
    }
}

#pragma mark 再次输入密码，确认框结束输入事件
-(void)confirmPWDTFEditingEnd
{
    if (![confirmPWTF.text isEqualToString:inputPWTF.text] || [confirmPWTF.text isEqualToString:@""]) {
        _confirPwdLegal = NO;
        _confirPwdTFWarningLab.text = @"两次输入密码不一致";
    }
    else
    {
        _confirPwdLegal = YES;
        _confirPwdTFWarningLab.text = @"";
    }
    
}
#pragma mark - 导航栏左边按钮点击后，触发方法
- (void)backIsClicked {
    if (_timer && [_timer isValid]) {
        [_timer invalidate];
        _timer = nil;
    }
    LoginViewController *loginVC = [[LoginViewController alloc] init];
    
    [self.navigationController pushViewController:loginVC animated:YES];
}

#pragma mark - 导航栏右边按钮点击后，触发方法
- (void)cancelIsClicked {
    if ( _timer && [_timer isValid]) {
        [_timer invalidate];
        _timer = nil;
    }
    //用于取消用户的所有操作
    phoneTF.text = @"";
    nickNameTF.text = @"";
    inputIdentifyingCode.text = @"";
    inputPWTF.text = @"";
    confirmPWTF.text = @"";
    
    _phoneTFWarningLab.text = @"";
    _nickTFWarningLab.text = @"";
    _indentifyCodeTFWarningLab.text = @"";
    _pwdTFWarningLab.text = @"";
    _confirPwdTFWarningLab.text = @"";
}

- (void)register_isBtnIsClicked:(UIButton *)sender {
    isBtn.selected = !isBtn.selected;
}

#pragma mark - 获取验证码按钮被点击，触发方法
- (void)getIdentifyingCodeBtnIsClicked:(UIButton *)sender {
    self.isClickIdentify = YES;
    _phoneTFWarningLab.text = @"";
    
    if ([nickNameTF.text isEqualToString:@""] || nickNameTF.text.length < 2) {
        _nickTFWarningLab.text = @"昵称不合法";
        return;
    }
    
    if ([_timer isValid]) {
        //表示计时器正在运行，不能再点击了
        return;
    }
    
    [self verifyPhoneWhetherLegal];
    
}

#pragma mark --获取验证码的函数
-(void)getIdentifyCode
{
    _timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(TimerBegins) userInfo:nil repeats:YES];
    
    if (phoneTF.text.length == 11 && nickNameTF.text.length > 2) {
        //获取验证码
        NSDictionary *dicx;
        type = @"Ios";
        key = @".5Xf_01KXd352s177Jx3wxXc074poII";
        time = @"yyyyMMddHHmmss";
        //sign 需要MD5加密方式. 传入字符串（time+type+key），需要用到字符串拼接。
        NSString *str = [[NSString alloc] initWithFormat:@"%@%@%@", time, type, key];
        sign = [MyMD5 md5:str];
        dicx = @{@"type" : type, @"key" : key, @"time" : time, @"sign" : sign, @"phone" : phoneTF.text};
        AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
        NSString *postStr = [NSString stringWithFormat:@"%@/terminal/smsapi",localRequestUrl];
        [manager POST:postStr parameters:dicx constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
            
        } progress:^(NSProgress * _Nonnull uploadProgress) {
            
        } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            NSLog(@"verifyCode = %@", responseObject[@"data"][@"verifycode"]);
            receiveIdentifyingCode = responseObject[@"data"][@"verifycode"];
            
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            NSLog(@"获取验证码失败");
            //弹出提示框“获取验证码失败”；
            [FileDownloadTool alert:@"获取验证码失败" view:self.view];
        }];
        
    } else {
        getIdentifyingCodeBtn.userInteractionEnabled = NO;
        NSLog(@"qwertr");
    }
    
}

#pragma mark - 注册按钮点击触发方法
- (void)registerBtnIsClicked:(UIButton *)sender {
    
    _confirPwdTFWarningLab.text = @"";
    [_isObserveAgreement removeFromSuperview];
    if (isBtn.selected) {
        _isObserveAgreement = [[UILabel alloc] initWithFrame:CGRectMake(kMargin, CGRectGetMaxY(isBtn.frame), kScreenwidth - 2*kMargin, 2*kMargin)];
        _isObserveAgreement.text = @"请遵守协议";
        _isObserveAgreement.textAlignment = NSTextAlignmentRight;
        _isObserveAgreement.textColor = [UIColor redColor];
        _isObserveAgreement.font = [UIFont systemFontOfSize:12];
        [self.view addSubview:_isObserveAgreement];
        return;
        
    } else if (phoneTF.text.length == 0 || nickNameTF.text.length == 0 ||inputIdentifyingCode.text.length == 0 || inputPWTF.text.length == 0 || confirmPWTF.text.length == 0 ) {
        
        UIAlertController *alertVc = [UIAlertController alertControllerWithTitle:@"注册失败" message:@"请完善以上信息" preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *action = [UIAlertAction actionWithTitle:@"确定" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
        }];
        [alertVc addAction:action];
        [self presentViewController:alertVc animated:YES completion:nil];
        return;
    }
    if (!_phoneLegal || !_nickLegal || !_indetifyCodeLegal || !_confirPwdLegal) {
        [FileDownloadTool alert:@"信息输入有误" view:self.view];
        return;
    }
    if (![receiveIdentifyingCode isEqualToString:inputIdentifyingCode.text]) {
        _indentifyCodeTFWarningLab.text = @"验证码有误";
        return;
    }
    if (![inputPWTF.text isEqualToString:confirmPWTF.text]) {
        _confirPwdTFWarningLab.text = @"两次密码不一致";
        return;
    }
    
    
    [_isObserveAgreement removeFromSuperview];
    
    NSDictionary *dicx;
    type = @"Ios";
    key = @".5Xf_01KXd352s177Jx3wxXc074poII";
    time = @"yyyyMMddHHmmss";
    //sign 需要MD5加密方式. 传入字符串（time+type+key），需要用到字符串拼接。
    NSString *str = [[NSString alloc] initWithFormat:@"%@%@%@", time, type, key];
    sign = [MyMD5 md5:str];
    login_type = @"2";
    dicx = @{@"type" : type, @"key" : key, @"time" : time, @"sign" : sign, @"login_type" : login_type, @"name" : phoneTF.text, @"pwds" : inputPWTF.text, @"nick_name" : nickNameTF.text};
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    NSString *postStr = [NSString stringWithFormat:@"%@/terminal/register",localRequestUrl];
    [manager POST:postStr parameters:dicx constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"%@", responseObject);
        if ([responseObject[@"status"] isEqualToString:@"9002"]) {
            //注册成功
            if (_timer && [_timer isValid]) {
                [_timer invalidate];
                _timer = nil;
            }
#pragma mark ---注册成功后没有提示，并且不能自动跳转到登陆界面(考虑用弹出框做，点击确定了跳转至登陆界面)
            UIAlertController *regAlert = [UIAlertController alertControllerWithTitle:@"注册帐号" message:@"注册成功，现在去登录" preferredStyle:UIAlertControllerStyleAlert];
            UIAlertAction *okB = [UIAlertAction actionWithTitle:@"好" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
                //跳转到登录页面。
                LoginViewController *loginVC = [[LoginViewController alloc] init];
                [self.navigationController pushViewController:loginVC animated:YES];
            }];
            [regAlert addAction:okB];
            [self presentViewController:regAlert animated:NO completion:nil];

        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        [FileDownloadTool alert:@"注册失败" view:self.view];
    }];
    
    
}


#pragma mark - UITextFieldDelegate Methods
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    if (textField.tag == 100) {
        return [self validateNumber:string andRange:range ofTextField:textField andLength:11];
    }
    else if(textField.tag == 101)
    {
        return [self validateNumber:string andRange:range ofTextField:textField andLength:10];
    }
    return YES;
}

//限制输入框只能输入length个长度字符
- (BOOL)validateNumber:(NSString*)replaceStr andRange:(NSRange)range ofTextField:(UITextField *)textField andLength:(unsigned int)length{
    
    if ([replaceStr isEqualToString:@"\n"]) {
        return YES;
    }
    NSString * toBeString = [textField.text stringByReplacingCharactersInRange:range withString:replaceStr]; //得到输入框的内容
    if ([toBeString length] > length) { //如果输入框内容大于20则弹出警告
        textField.text = [toBeString substringToIndex:length];
        return NO;
    }
    return YES;
}

#pragma mark - 计时器开始工作
- (void)TimerBegins {
    
    _second --;
    NSLog(@"second%ld", (long)_second);
    [getIdentifyingCodeBtn setTitle:[NSString stringWithFormat:@"%.2ld秒", (long)_second] forState:(UIControlStateNormal)];
    if (_second == 0) {
        [_timer invalidate];
        _timer = nil;
        [getIdentifyingCodeBtn setTitle:@"获取验证码" forState:(UIControlStateNormal)];
        _second = 60;
    }
}

#pragma amrk - 智慧登山服务协议Btn点击
- (void)agreementBtnIsClicked {
    AgreementViewController *agreementVc = [[AgreementViewController alloc] init];
    
    UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:agreementVc];
    
    [self presentViewController:nav animated:YES completion:nil];
    
}

-(void)dealloc
{
    if ([_timer isValid]) {
        [_timer invalidate];
        _timer = nil;
    }
}

////////////////////////////////////////////
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    //Dispose of any resources that can be recreated.
}

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