//
//  RDSLoginVerifyCodeVC.m
//  SmartLightForBigFish
//
//  Created by coderYK on 2017/11/17.
//  Copyright © 2017年 RD. All rights reserved.
//

#import "RDSLoginVerifyCodeVC.h"
#import "WLCaptcheButton.h"
#import "RDSUserProtocolViewController.h"
#import "NSString+verify.h"
#import "UIView+RDSClip.h"
#import "UIImage+Extension.h"
#import "RDSRootControl.h"
#import "RDSLoginPwdCodeVC.h"
#import "RDCheckAppVersion.h"

@interface RDSLoginVerifyCodeVC ()<UITextFieldDelegate>

@property (weak, nonatomic) IBOutlet UIView *phoneView;
@property (weak, nonatomic) IBOutlet UIView *verifyCodeView;

@property (weak, nonatomic) IBOutlet UIButton *loginBtn;
@property (weak, nonatomic) IBOutlet WLCaptcheButton *verifyCodeBtn;
@property (weak, nonatomic) IBOutlet UITextField *phoneTF;
@property (weak, nonatomic) IBOutlet UITextField *verifyCodeTF;
@property (weak, nonatomic) IBOutlet UITextField *pwdTF;
@property (weak, nonatomic) IBOutlet UIButton *agreeBtn;
@property (weak, nonatomic) IBOutlet UIButton *userAgreement;
@property (weak, nonatomic) IBOutlet UILabel *userAgreementLab;

@end

@implementation RDSLoginVerifyCodeVC

- (void)viewDidLoad {
    [super viewDidLoad];
    
    // 隐藏导航栏
    self.fd_prefersNavigationBarHidden = YES;
    
    self.view.backgroundColor = [UIColor whiteColor];

     
    [self p_setupTF];
    
    [self.verifyCodeBtn rds_setCornerRadius:self.verifyCodeBtn.rds_height*0.5 borderLineWidth:1 lineColor:RDSGreenColor];
    
    
    _phoneTF.text = TheDataManager.phone;
//    _verifyCodeTF.text = TheDataManager.verifyCode;
    
    
//    if(!TheDataManager.isFirstTimeAgree){
//        [TheAlertCtrl rds_alertWithTitle:@"用户协议和隐私协议" message:@"\n欢迎使用永续绿建五恒 APP，我们非常重视您的隐私保护和个人信息保护，使用本软件的过程中我们会严格按照法律规定收集存储和使用您的个人信息，未经您的同意我们不会向第三方提供您的任何信息，您可以阅读《用户协议》 和《隐私协议》 全文了解详细信息。如您同意，请点击“同意”开始接受我们的服务。" cancel:@"暂不使用" sure:@"同意" cancelColor:nil sureColor:nil cancelAction:^{
//
//            // Home键退出后台动画效果，此时后台还是挂起状态
//            [[UIApplication sharedApplication] performSelector:@selector(suspend)];
//            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
//                 // 杀掉应用，这里会有警告⚠️忽略即可，强迫症的话就使用exit(0)吧
//                 [[UIApplication sharedApplication] performSelector:@selector(terminateWithSuccess)];
//            });
//
//        } sureAction:^{
//            TheDataManager.isFirstTimeAgree = YES;
//        }];
//    }
    
    // 检查更新
    [TheCheckAppVersion checkUpdate];
    
    // 这是rootControl 自动登录时会先进入这个页面，所有先隐藏
    if(!self.isPushVc){
        self.view.alpha = 0;
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            self.view.alpha = 1;
        });
    }
}

- (void)viewDidLayoutSubviews{
    [super viewDidLayoutSubviews];
    
    _phoneView.layer.cornerRadius = _phoneView.rds_height/2;
    _verifyCodeView.layer.cornerRadius = _verifyCodeView.rds_height/2;
    
    _verifyCodeBtn.layer.cornerRadius = _verifyCodeBtn.rds_height/2;
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    
    _agreeBtn.selected = NO;
}

#pragma mark - Action

- (IBAction)p_onPwdLogin {
    
    if(_isPushVc){
        [self popViewControllerAnimated:YES];
    }else{
        RDSLoginPwdCodeVC *vc = [[RDSLoginPwdCodeVC alloc] init];
        vc.isPushVc = YES;
        [self pushViewController:vc animated:YES];
    }
    
}

// 登录
- (IBAction)p_onLogin {
    
    if (![self.phoneTF.text isPhoneNum]) {
        [RDSHudShower showBottomToast:@"请输入正确的手机号码"];
        return;
    }
    else if (self.verifyCodeTF.text.length < 1){
        [RDSHudShower showBottomToast:@"请输入验证码"];
        return;
    }
    else if (!self.agreeBtn.isSelected){
        [RDSHudShower showBottomToast:@"请先阅读并同意用户协议"];
        return;
    }

    
    [RDSHudShower showWithStatus:@"正在登录账户…" autoDismiss:NO];
    RDS_WEAKSELF(weakSelf)
    [RDSDemoApiHelper rds_loginWithVerifyCodePhone:self.phoneTF.text code:self.verifyCodeTF.text success:^(id responseObject) {
        
        if ([responseObject[@"code"] intValue] != 0) {
            [RDSHudShower showBottomToast:responseObject[@"message"]];
        }
        else{
            [RDSHudShower dismissHUD];
            [RDSRootControl shareControl].isLoginSuccess = YES;
            
            NSDictionary *data = responseObject[@"data"];
            TheDataManager.token = [NSString stringWithFormat:@"%@ %@",data[@"token_type"], data[@"access_token"]];
            TheDataManager.verifyCode = weakSelf.verifyCodeTF.text;
            TheDataManager.isFirstLogin = [data[@"app_first_login"] boolValue];
        }
        
    } failure:^(NSError *error) {
        [RDSHudShower showBottomToast:@"连接服务器失败"];
    }];
    
    

}


- (IBAction)p_getVerifyCode:(WLCaptcheButton *)verifyCodeBtn {
    
    if (![self.phoneTF.text isPhoneNum]) {
        [RDSHudShower showCenterToast:@"请输入正确的手机号码"];
        return;
    }
    
    //TheDataManager.phone = self.phoneTF.text;
    _verifyCodeTF.text = @"";
    [_verifyCodeTF becomeFirstResponder];
    
    [verifyCodeBtn fire];
    
    [RDSHudShower showWithStatus:@"正在获取验证码…" autoDismiss:YES];
    RDS_WEAKSELF(weakSelf)
    [RDSDemoApiHelper rds_getVerifyCodePhone:self.phoneTF.text type:1 success:^(id responseObject) {
        
        if ([responseObject[@"code"] intValue] != 0) {
            [RDSHudShower showBottomToast:responseObject[@"message"]];
        }
        else{
            [RDSHudShower showBottomToast:@"获取验证码成功"];
            
        }
        
    } failure:^(NSError *error) {
        [RDSHudShower showBottomToast:@"连接服务器失败"];
        DDLog(@"json data error:/n%@", error.description);
    }];
    


    [self.verifyCodeTF becomeFirstResponder];
}

// 阅读并同意
- (IBAction)p_onAgreeBtnClick:(UIButton *)sender {
    
    sender.selected = !sender.selected;
}

// 点击用户协议
- (IBAction)p_onUserAgreementClick {
    
    RDSUserProtocolViewController *userProtocolVC = [[RDSUserProtocolViewController alloc] init];
    userProtocolVC.url = kUserAgreement;
    userProtocolVC.vcTitle = @"用户协议";
    [self pushViewController:userProtocolVC animated:YES];
}

// 点击隐私政策
- (IBAction)p_onPrivacyPolicyClick {
    
    RDSUserProtocolViewController *userProtocolVC = [[RDSUserProtocolViewController alloc] init];
    userProtocolVC.url = kPrivacyPolicy;
    userProtocolVC.vcTitle = @"隐私政策";
    [self pushViewController:userProtocolVC animated:YES];
}


- (IBAction)p_onPwdShowBtnClick:(UIButton *)sender {
    
    sender.selected = !sender.selected;
    _pwdTF.secureTextEntry = sender.selected;
    
}

#pragma mark - UITextFieldDelegate

- (void)p_setupTF {
    
    self.phoneTF.delegate = self;
    self.verifyCodeTF.delegate = self;
    self.pwdTF.delegate = self;
    
    
}

// 密文输入时，点击光标不清空
//- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
// 
//    NSString *updatedString = [textField.text stringByReplacingCharactersInRange:range withString:string];
// 
//    textField.text = updatedString;
// 
//    return NO;
//}

- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    
    if (textField == self.phoneTF) {
        [self.verifyCodeTF becomeFirstResponder];
    }
    else if (textField == self.verifyCodeTF) {
        [self.pwdTF becomeFirstResponder];
    }
    else {
        [self.pwdTF resignFirstResponder];
        [self p_onLogin];
    }
    return YES;
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    [self.view endEditing:YES];
}

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


- (void)dealloc{
    DDLog(@"dealloc~~");
}
@end
