//
//  BPViewController.m
//  Open
//
//  Created by 雷俊博 on 2019/6/30.
//  Copyright © 2019 黄江涛 . All rights reserved.
//

#import "BPViewController.h"
#import "Constants.h"
#import <Masonry.h>
#import "Tools.h"


#define TIMECOUNT 60

@interface BPViewController ()<UITextFieldDelegate>

@property (nonatomic, strong)UITextField *tf_phoneNumber;


@property (nonatomic, strong)UITextField *tf_VerificationCode;

@property (nonatomic, strong)UIButton *btn_VerificationCode;

@property (nonatomic, strong)UIButton *btn_BindPhoneNumber;


@end

@implementation BPViewController
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    if ([self.from isEqualToString:@"other"]) {
        [self.navigationController setNavigationBarHidden:YES animated:animated];
    }
    
}
#pragma mark - life cycle
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.view.backgroundColor = [UIColor whiteColor];
    
    [self.view addSubview:self.tf_phoneNumber];
    [self.view addSubview:self.tf_VerificationCode];
    
    [self.view addSubview:self.btn_VerificationCode];
    [self.view addSubview:self.btn_BindPhoneNumber];
    
    UIBarButtonItem *backItem = [[UIBarButtonItem alloc] initWithImage:[[UIImage imageNamed:@"back"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal]  style:UIBarButtonItemStylePlain target:self action:@selector(back)];
    self.navigationItem.leftBarButtonItem = backItem;
    
    [self.navigationController.navigationBar setTitleTextAttributes:@{NSForegroundColorAttributeName : [UIColor blackColor],
                                                                      NSFontAttributeName : [UIFont fontWithName:@"Helvetica-Bold" size:17]}];
    
    [_tf_phoneNumber addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
    [_tf_VerificationCode addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
    
    
    if ([self.from isEqualToString:@"other"]) {
        [self navigationConfig];
    }
}

- (void)navigationConfig
{
    UIView *navView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, cl_kNavigationBarHeight)];
    navView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:navView];
    
    UIButton* backButton = [UIButton buttonWithType:UIButtonTypeCustom];
    
    backButton.frame = CGRectMake(0, cl_kStatusBarHeight, 80, 44);
    
    [backButton setImage:[UIImage imageNamed:@"back"] forState:UIControlStateNormal];
    [backButton addTarget:self action:@selector(back) forControlEvents:UIControlEventTouchUpInside];
    
    [navView addSubview:backButton];
    
    UILabel *titleLabel = [UILabel new];
    titleLabel.textColor = [UIColor blackColor];
    titleLabel.font = [UIFont fontWithName:@"Helvetica-Bold" size:17];
    [navView addSubview:titleLabel];
    titleLabel.text = self.title;
    [titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(navView);
        make.top.offset(cl_kStatusBarHeight);
        make.height.offset(44);
    }];
    
}


- (void)viewWillLayoutSubviews
{
    [super viewWillLayoutSubviews];
    
    [self.tf_phoneNumber mas_makeConstraints:^(MASConstraintMaker *make) {
        CGFloat topDistance = (cl_kNavigationBarHeight + 10);
        make.top.offset( topDistance * HEIGHTRADIU);
        make.left.offset(20 * WIDTHRADIU);
        make.right.offset(-20 * WIDTHRADIU);
        make.height.offset(40*WIDTHRADIU);
    }];
    
    [self.tf_VerificationCode mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.tf_phoneNumber.mas_bottom).offset(10 * WIDTHRADIU);
        make.left.equalTo(self.tf_phoneNumber);
        make.width.offset(230 * WIDTHRADIU);
        make.height.equalTo(self.tf_phoneNumber);
    }];
    
    [self.btn_VerificationCode mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.tf_VerificationCode.mas_right).offset(5 *WIDTHRADIU);
        make.centerY.equalTo(self.tf_VerificationCode);
    }];
    
    [self.btn_BindPhoneNumber mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.tf_VerificationCode.mas_bottom).offset(30 * WIDTHRADIU);
        make.left.equalTo(self.tf_phoneNumber.mas_left).offset(5 * WIDTHRADIU);
        make.right.equalTo(self.tf_phoneNumber.mas_right).offset(-5 * WIDTHRADIU);
        make.height.offset(45 * WIDTHRADIU);
    }];
    
}

#pragma mark - UITextFieldDelegate
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [textField resignFirstResponder];
    return YES;
}




#pragma mark - event reponse
- (void)back
{
    if ([self.from isEqualToString:@"other"]) {
        [self.navigationController dismissViewControllerAnimated:YES completion:nil];
    }else{
        NSLog(@"返回了");
        [self.navigationController popViewControllerAnimated:YES];
    }
   
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    [self.view endEditing:YES];
}
- (void)textFieldDidChange:(UITextField *)textField{
    
    if (_tf_phoneNumber.text.length >= 11 && _tf_VerificationCode.text.length >= 4) {
        _btn_BindPhoneNumber.userInteractionEnabled = YES;
        _btn_BindPhoneNumber.backgroundColor = RGBCOLOR(51, 138, 208);
    }else{
        _btn_BindPhoneNumber.userInteractionEnabled = NO;
        _btn_BindPhoneNumber.backgroundColor = RGBCOLOR(197, 197, 197);
    }
    
    if ([textField isEqual:_tf_phoneNumber]) {
        if (textField.text.length >=11) {
            textField.text = [textField.text substringToIndex:11];
        }
    }else if ([textField isEqual:_tf_VerificationCode]){
        if (textField.text.length >=4) {
            textField.text = [textField.text substringToIndex:4];
        }
    }
    
}

- (void)bindPhoneClick:(UIButton *)btn
{
    
    [self.view endEditing:YES];
    if (![Tools isMobileNumber:_tf_phoneNumber.text]) {
        [SVProgressHUD showErrorWithStatus:@"请输入正确的手机号"];
        return;
    }
    
    [self SenderthirdWeixinStr:self.UID andTelephone:self.tf_phoneNumber.text andidentitfityUdid:nil andIdentitfyId:self.Id andPicId:self.tf_VerificationCode.text cus_name:self.wxName];
    
}

- (void)vertificationClick:(UIButton *)sender
{
    [self.view endEditing:YES];
    NSLog(@"123");
    if (![Tools isMobileNumber:_tf_phoneNumber.text]) {
        [SVProgressHUD showErrorWithStatus:@"请输入正确的手机号"];
        return;
    }
    
    NSDictionary *params = @{
                             @"telphone":[EnercryTool encryptUseDES:self.tf_phoneNumber.text key:DESKEY],
                             @"Id":self.Id,
                             @"targetflag":@1004,
                             @"uid":self.UID
                             };
    [SVProgressHUD show];
    NSString * url =[IPDIZHI stringByAppendingString:@"/socialsecurity/kankan/getVerificationcode"];
    NSString *newUrl =  [url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    
    [logNetModel getVerificationCodeWithUrl:newUrl Params:params completionHandle:^(lodModel *model, NSError * error) {
        
        [SVProgressHUD dismiss];
        if ([model.code isEqualToString:@"0"]) {
            __block NSInteger second = TIMECOUNT;
            //(1)
            dispatch_queue_t quene = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
            //(2)
            dispatch_source_t timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, quene);
            //(3)
            dispatch_source_set_timer(timer, DISPATCH_TIME_NOW, 1 * NSEC_PER_SEC, 0 * NSEC_PER_SEC);
            //(4)
            dispatch_source_set_event_handler(timer, ^{
                dispatch_async(dispatch_get_main_queue(), ^{
                    if (second == 0) {
                        sender.userInteractionEnabled = YES;
                        [sender setTitle:[NSString stringWithFormat:@"获取验证码"] forState:UIControlStateNormal];
                         [_btn_VerificationCode setTitleColor:RGBCOLOR(23, 123, 206) forState:UIControlStateNormal];
                        second = TIMECOUNT;
                        //(6)
                        dispatch_cancel(timer);
                    } else {
                        sender.userInteractionEnabled = NO;
                        [sender setTitle:[NSString stringWithFormat:@"%ld秒后重新获取",(long)second] forState:UIControlStateNormal];
                         [_btn_VerificationCode setTitleColor:RGBCOLOR(197, 197, 197) forState:UIControlStateNormal];
                        second--;
                    }
                });
            });
            //(5)
            dispatch_resume(timer);
        }else{
            codeSelected *code = [codeSelected MustTakeReturn:[model.code intValue]];
            [code returnCodeMethod];
        }
    }];
    
}









#pragma mark - 绑定手机号接口
-(void)SenderthirdWeixinStr:(NSString *)weixinStr andTelephone:(NSString*)telphone andidentitfityUdid:(NSString*)telephonePwd andIdentitfyId:(NSString*)identitfyId andPicId:(NSString *)picId cus_name:(NSString *)cus_name{
    
//    WeakSelf
    
    [logNetModel getLogMessage4:weixinStr andTelephone:telphone andLoginpassword:telephonePwd andUid:nil andl:2 andweixinId:identitfyId andPicId:picId cus_name:cus_name completionHandle:^(lodModel * model, NSError *error) {
        if (error) {
                   [SVProgressHUD showErrorWithStatus:@"网络出错"];
                   return;
               }
               //test
               [SVProgressHUD dismiss];
               if ([model.status isEqualToString:@"0"]) {
                   
                   [[NSUserDefaults standardUserDefaults] setBool:NO forKey:@"startAutoLoginState"];
                   //设置第一次登入为yes
                   [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"firstlog"];
                   //存储登录时间
                    NSDate* loginDate = [NSDate date];
                    [getPeopleID saveLoginTime:loginDate];
                   //昵称
                   if (model.userinfo.cus_name)
                   {
                       
                       NSString *cusName = model.userinfo.cus_name;
                       [getPeopleID getPeopletitle:cusName];
                       
                       
                   } else {
                       [getPeopleID getPeopletitle:self.wxName];
                   }
                   //存储默认登录手机号
                   if (![Tools isBlankString:model.userinfo.telphone]) {
                       [getPeopleID saveDefaultLoginAccount:model.userinfo.telphone];
                   }
                   //存储默认登录密码
                   if (![Tools isBlankString:model.userinfo.cus_password]) {
                       [getPeopleID saveDefaultLoginPassword:model.userinfo.cus_password];
                   }
                   
                   //存储用户头像
                   if ([Tools isBlankString:picId]) {
                       if (![Tools isBlankString:model.userinfo.photo]) {
                           [getPeopleID getPeoplePhoto:model.userinfo.photo];
                       }
                   }else{
                       if (![Tools isBlankString:self.wxPhotoUrl]) {
                           [getPeopleID getPeoplePhoto:self.wxPhotoUrl];
                       }
                   }
                   
                     
                   [getPeopleID getPeopleID:model.userinfo.ID];
                     
                   
                   //存储手机号
                   NSString *userBindTel = model.userinfo.telphone;
                   if (![Tools isBlankString:userBindTel]) {
                       if ([model.userinfo.telphone containsString:@"undo"]) {
                           userBindTel = [model.userinfo.telphone stringByReplacingOccurrencesOfString:@"undo" withString:@""];
                       }
                       
                       [getPeopleID getPeopleIphoneNmber:userBindTel];
                   }
                   
                   
                   if (model.userinfo.account_type == 0) {
                       [getPeopleID getpeopleLimitedAuthority:YES];
                   }else
                   {
                       [getPeopleID getpeopleLimitedAuthority:NO];
                   }
                   
                   //保存用户所在的省份
                   NSString *provinceName = model.userinfo.provinceName;
                   if ([Tools isBlankString:provinceName]) {
                        NSString *province = [UserDefault objectForKey:@"locationProvince"];
                         if ([Tools isBlankString:province]) {
                             [getPeopleID getProvince:@"上海市"];
                         }else{
                             [getPeopleID getProvince:province];
                         }
                     }else{
                         [getPeopleID getProvince:provinceName];
                     }
                   
                   
                   [UserDefault setObject:model.userinfo.token forKey:@"loginToken"];
                   //[GeTuiSdk bindAlias:[NSString stringWithFormat:@"kksh_%ld",model.userinfo.ID] andSequenceNum:[NSString stringWithFormat:@"%ld",model.userinfo.ID]];
                   
                   
                   [[NSNotificationCenter defaultCenter] postNotificationName:KKSBLoginSuccessNotificationName object:nil userInfo:nil];
                   
                   if (self.block) {
                       self.block(YES);
                   }
                   [self.navigationController dismissViewControllerAnimated:YES completion:nil];
                   
               }else{
                   codeSelected *code = [codeSelected MustTakeReturn:[model.status intValue]];
                   [code returnCodeMethod];
               }
    }];
    
    
}

#pragma mark - getters and setters
- (UITextField *)tf_phoneNumber
{
    if (!_tf_phoneNumber) {
        _tf_phoneNumber = [[UITextField alloc]init];
        _tf_phoneNumber.placeholder = @"请输入手机号";
        _tf_phoneNumber.borderStyle = UITextBorderStyleRoundedRect;
        _tf_phoneNumber.keyboardType = UIKeyboardTypeNumberPad;
        _tf_phoneNumber.delegate = self;
    }
    return _tf_phoneNumber;
}

- (UITextField *)tf_VerificationCode
{
    if (!_tf_VerificationCode) {
        _tf_VerificationCode = [[UITextField alloc]init];
        _tf_VerificationCode.placeholder = @"请输入验证码";
        _tf_VerificationCode.borderStyle = UITextBorderStyleRoundedRect;
        _tf_VerificationCode.keyboardType = UIKeyboardTypeNumberPad;
        _tf_VerificationCode.delegate = self;
        
        if (@available(iOS 12.0, *)) {

                _tf_VerificationCode.textContentType = UITextContentTypeOneTimeCode;

              }
    }
    return _tf_VerificationCode;
}

- (UIButton *)btn_VerificationCode
{
    if (!_btn_VerificationCode) {
        _btn_VerificationCode = [UIButton buttonWithType:UIButtonTypeCustom];
        [_btn_VerificationCode setTitle:@"获取验证码" forState:UIControlStateNormal];
        _btn_VerificationCode.titleLabel.font = [UIFont systemFontOfSize:15*WIDTHRADIU];
        [_btn_VerificationCode setTitleColor:RGBCOLOR(23, 123, 206) forState:UIControlStateNormal];
        [_btn_VerificationCode addTarget:self action:@selector(vertificationClick:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _btn_VerificationCode;
}

- (UIButton *)btn_BindPhoneNumber
{
    if (!_btn_BindPhoneNumber) {
        _btn_BindPhoneNumber = [UIButton buttonWithType:UIButtonTypeCustom];
        [_btn_BindPhoneNumber setTitle:@"绑定" forState:UIControlStateNormal];
        _btn_BindPhoneNumber.backgroundColor = RGBCOLOR(197, 197, 197);
        _btn_BindPhoneNumber.layer.cornerRadius = 5;
        [_btn_BindPhoneNumber setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [_btn_BindPhoneNumber addTarget:self action:@selector(bindPhoneClick:) forControlEvents:UIControlEventTouchUpInside];
        _btn_BindPhoneNumber.userInteractionEnabled = NO;
    }
    return _btn_BindPhoneNumber;
}

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