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

#import "WXLoginViewController.h"
#import "LoginView.h"
#import "Constants.h"
#import "LoginView.h"

#import "BPViewController.h"

#import "CTAPIBaseManager.h"

#import <Masonry.h>

#import "WXApi.h"
#import "WXApiManager.h"

#import <AuthenticationServices/AuthenticationServices.h>
#import "SignInApple.h"
//mob一键登录
#import <SecVerify/SVSDKHyVerify.h>
#import "CustomExample.h"
#import "PasswordLoginViewController.h"
#import "SMSLoginViewController.h"
@interface WXLoginViewController ()<loginBtnDelegate,WXApiDelegate,WXApiManagerDelegate,SVSDKVerifyDelegate>
{
    NSInteger Id;//用户id
    NSString *uid;//微信id
    NSString *telphone;//手机号
    NSString *photoUrl;//微信头像
    NSString *accountName;//微信昵称
    NSString *appId;//闪验appId
    NSString *accessToken;//闪验accessToken
    NSString *telecom;//闪验运营商
    NSString *timestamp;//闪验时间戳
    NSString *randoms;//闪验随机数
    NSString *version;//闪验版本
    NSString *device;//闪验设备
    NSString *sign;//闪验签名
}



@property (nonatomic, strong) UIImageView * imgView_topIcon;

@property (nonatomic, strong) UILabel *lab_title;

@property (nonatomic, strong) UIButton *btn_WXLogin;

@property (nonatomic, strong) LoginView *directlyLogin;

@property (nonatomic, strong) LoginView *smsLogin;

@property (nonatomic, strong) LoginView * passwordLogin;

@property (nonatomic, strong) UIView *leftLine;

@property (nonatomic, strong) UILabel *middleLab;

@property (nonatomic, strong) UIView *rightLine;
//自定义UI设置示例
@property (nonatomic,strong)id uiMakerExample;
//如需引用授权页vc对象，请使用weak弱引用
@property (nonatomic,weak)UIViewController * authPageVc;
// 防止被释放，回调方法不会走，或者也可以把SignInApple这个类写成单例
@property (nonatomic, strong) SignInApple *signInApple;

@property (nonatomic, strong)WXLoginViewController *wxVC;

@property (nonatomic, strong)SMSLoginViewController *smsVC;

@property (nonatomic, strong)PasswordLoginViewController *passwordVC;

@end

@implementation WXLoginViewController
#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.imgView_topIcon];
    [self.view addSubview:self.lab_title];
    [self.view addSubview:self.btn_WXLogin];
    [self.view addSubview:self.directlyLogin];
    [self.view addSubview:self.smsLogin];
    [self.view addSubview:self.passwordLogin];
    
    [self.view addSubview:self.leftLine];
    [self.view addSubview:self.middleLab];
    [self.view addSubview:self.rightLine];
    
    //mob预取号
    [SVSDKHyVerify preLogin:^(NSDictionary * _Nullable resultDic, NSError * _Nullable error) {
        //判断预取号是否成功,返回resultDic :  {“operatorName” : “中国移动”} ，可能返回 中国移动、中国联通、中国电信，error : error为nil，即为预取号成功.
        if (error == nil && resultDic != nil && [resultDic isKindOfClass:NSDictionary.class]) {
            //成功
            NSLog(@"mob预取号成功");
        }else{
            //失败
        }
    }];
    
   
    
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    //[self perfomExistingAccount];
}

- (void)viewWillLayoutSubviews
{
    [super viewWillLayoutSubviews];
    [self setupUI];
}

- (void)dealloc
{
    NSLog(@"WXLoginViewController已销毁");
}


- (void)configUI{
    

}

// 自己用UIButton按钮调用处理授权的方法
- (void)didCustomBtnClicked{
    // 封装Sign In with Apple 登录工具类，使用这个类时要把类对象设置为全局变量，或者直接把这个工具类做成单例，如果使用局部变量，和IAP支付工具类一样，会导致苹果回调不会执行
    self.signInApple = [[SignInApple alloc] init];
    self.signInApple.vc = self;
    __weak typeof(self) weakSelf = self;
    self.signInApple.SignInApple = ^(id  _Nonnull objc, NSString * _Nonnull Id) {
        NSString*status = [NSString stringWithFormat:@"%@",objc[@"status"]];
        typeof(weakSelf) __strong strongSelf = weakSelf;
        if ([status isEqualToString:@"0"]) {
            [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"firstlog"];
                      lodModel*model = [lodModel mj_objectWithKeyValues:objc];
                     if (model.userinfo.cus_name)
                     {
                         
                         NSString *cusName = model.userinfo.cus_name;
                         [getPeopleID getPeopletitle:cusName];
                         
                         
                         
                     }
                     
                        [getPeopleID saveDefaultLoginAccount:model.userinfo.telphone];
                     
                        [getPeopleID saveDefaultLoginPassword:model.userinfo.cus_password];
                      [getPeopleID getPeoplePhoto:model.userinfo.photo];
                     [getPeopleID getLoginType:@"appleLogin"];
                     
                     //存储登录时间
                     NSDate* loginDate = [NSDate date];
                     [getPeopleID saveLoginTime:loginDate];
                     
                      [getPeopleID getPeoplePhoto:model.userinfo.photo];
                     [getPeopleID getPeopleID:model.userinfo.ID];
                     
                    
                     [getPeopleID getPeopleIphoneNmber:model.userinfo.telphone];
                     if (model.userinfo.account_type == 0) {
                         [getPeopleID getpeopleLimitedAuthority:YES];
                     }else
                     {
                         [getPeopleID getpeopleLimitedAuthority:NO];
                     }
           
                     [UserDefault setObject:model.userinfo.token forKey:@"loginToken"];
                     [getPeopleID socialSate:1];
                     //[GeTuiSdk bindAlias:[NSString stringWithFormat:@"kksh_%ld",model.userinfo.ID] andSequenceNum:[NSString stringWithFormat:@"%ld",model.userinfo.ID]];
                     [[NSNotificationCenter defaultCenter] postNotificationName:KKSBLoginSuccessNotificationName object:nil userInfo:nil];
                        
                        [weakSelf.navigationController dismissViewControllerAnimated:YES completion:^{
                            if (weakSelf.block) {
                                weakSelf.block(YES);
                            }
                        }];
                     
                     
                     [CTAPIBaseManager GET3:LoginCountUrl params:@{} completionHandler:^(id  _Nonnull responseObject, NSError * _Nonnull error) {

                                   }];
        }else if ([status isEqualToString:@"1031"]){
            
            NSDictionary*userInfo = objc[@"userinfo"];
            NSString* kId = [NSString stringWithFormat:@"%@",userInfo[@"id"]];
//            NSString* photo = [NSString validBlankStr:userInfo[@"photo"]];
//            NSString* cus_name = [EnercryTool decryptUseDES:[NSString validBlankStr:userInfo[@"cus_name"]] key:DESKEY] ? [EnercryTool decryptUseDES:[NSString validBlankStr:userInfo[@"cus_name"]] key:DESKEY] :@"";
          
           self->uid = Id;
           self->Id = kId.integerValue;
//           accountName = cus_name;
           self->photoUrl = @"https://i.rensheju.com/userPhoto/defaultPhoto.png";
          
         // [getPeopleID]
          
         
         BPViewController *bpVC = [[BPViewController alloc]init];
         bpVC.UID = strongSelf->uid;
         bpVC.Id = [NSString stringWithFormat:@"%ld",(long)strongSelf->Id];
         bpVC.wxName = [NSString blankString:strongSelf->accountName] ? @"" :strongSelf->accountName;
         bpVC.wxPhotoUrl = strongSelf->photoUrl;
         bpVC.title = @"绑定手机号";
         [strongSelf.navigationController pushViewController:bpVC animated:YES];
        }
    };
    [self.signInApple handleAuthorizationAppleIDButtonPress];
}

// 使用系统提供的按钮调用处理授权的方法
- (void)didAppleIDBtnClicked{
    // 封装Sign In with Apple 登录工具类，使用这个类时要把类对象设置为全局变量，或者直接把这个工具类做成单例，如果使用局部变量，和IAP支付工具类一样，会导致苹果回调不会执行
    self.signInApple = [[SignInApple alloc] init];
    self.signInApple.vc = self;
    __weak typeof(self) weakSelf = self;
    self.signInApple.SignInApple = ^(id  _Nonnull objc, NSString * _Nonnull Id) {
        NSString*status = [NSString stringWithFormat:@"%@",objc[@"status"]];
       if ([status isEqualToString:@"0"]) {
           [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"firstlog"];
                     lodModel*model = [lodModel mj_objectWithKeyValues:objc];
                    if (model.userinfo.cus_name)
                    {
                        
                        NSString *cusName = model.userinfo.cus_name;
                        [getPeopleID getPeopletitle:cusName];
                        
                        
                        
                    }
           
                    [getPeopleID saveDefaultLoginAccount:model.userinfo.telphone];
                    [getPeopleID saveDefaultLoginPassword:model.userinfo.cus_password];
                    
                    
                     [getPeopleID getPeoplePhoto:model.userinfo.photo];
                    [getPeopleID getLoginType:@"appleLogin"];
                    
                    //存储登录时间
                    NSDate* loginDate = [NSDate date];
                    [getPeopleID saveLoginTime:loginDate];
                    
                     [getPeopleID getPeoplePhoto:model.userinfo.photo];
                    [getPeopleID getPeopleID:model.userinfo.ID];
                    
                   
                    [getPeopleID getPeopleIphoneNmber:model.userinfo.telphone];
                    if (model.userinfo.account_type == 0) {
                        [getPeopleID getpeopleLimitedAuthority:YES];
                    }else
                    {
                        [getPeopleID getpeopleLimitedAuthority:NO];
                    }
           
          
                    [UserDefault setObject:model.userinfo.token forKey:@"loginToken"];
                    //[GeTuiSdk bindAlias:[NSString stringWithFormat:@"kksh_%ld",model.userinfo.ID] andSequenceNum:[NSString stringWithFormat:@"%ld",model.userinfo.ID]];
                    [getPeopleID socialSate:1];
                        [[NSNotificationCenter defaultCenter] postNotificationName:KKSBLoginSuccessNotificationName object:nil userInfo:nil];
                    
                    
           
           
                   
                   [weakSelf.navigationController dismissViewControllerAnimated:YES completion:^{
                       if (weakSelf.block) {
                           weakSelf.block(YES);
                       }
                   }];
                    
                    
                    [CTAPIBaseManager GET3:LoginCountUrl params:@{} completionHandler:^(id  _Nonnull responseObject, NSError * _Nonnull error) {

                                  }];
       }else if ([status isEqualToString:@"1031"]){
          
           
           
          NSDictionary*userInfo = objc[@"userinfo"];
           NSString* kId = [NSString stringWithFormat:@"%@",userInfo[@"id"]];
//           NSString* photo = [NSString validBlankStr:userInfo[@"photo"]];
           NSString* cus_name = [EnercryTool decryptUseDES:[NSString validBlankStr:userInfo[@"cus_name"]] key:DESKEY] ? [EnercryTool decryptUseDES:[NSString validBlankStr:userInfo[@"cus_name"]] key:DESKEY] :@"";
           
           self->uid = Id;
           self->Id = kId.integerValue;
           self->accountName = cus_name;
           self->photoUrl = @"https://i.rensheju.com/userPhoto/defaultPhoto.png";
           
          // [getPeopleID]

           UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"友情提示" message:@"是否绑定手机号,如不绑定,将影响您的认证操作" preferredStyle:UIAlertControllerStyleAlert];
           
           // 2.创建并添加按钮
              UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"去绑定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                  typeof(weakSelf) __strong strongSelf = weakSelf;
                  NSLog(@"OK Action");
                  BPViewController *bpVC = [[BPViewController alloc]init];
                  bpVC.UID = strongSelf->uid;
                  bpVC.Id = [NSString stringWithFormat:@"%ld",(long)strongSelf->Id];
                  bpVC.wxName = [NSString blankString:strongSelf->accountName] ? @"" :strongSelf->accountName;
                  bpVC.wxPhotoUrl = strongSelf->photoUrl;
                  bpVC.title = @"绑定手机号";
                  [strongSelf.navigationController pushViewController:bpVC animated:YES];
              }];
              UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"跳过" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
                  typeof(weakSelf) __strong strongSelf = weakSelf;
                  NSLog(@"Cancel Action");
                  [getPeopleID getLoginType:@"appleLogin"];
                  [UserDefault setInteger:1031 forKey:@"appleLoginState"];
                  [UserDefault setObject:Id forKey:@"appleId"];
                  [getPeopleID getPeopletitle:[EnercryTool encryptUseDES:cus_name key:DESKEY]];
                  [getPeopleID getPeopleID:kId.integerValue];
                  [getPeopleID getPeoplePhoto:strongSelf->photoUrl];
                  [getPeopleID getPeopleIphoneNmber:@""];
                  [UserDefault synchronize];
                  [strongSelf.navigationController dismissViewControllerAnimated:YES completion:nil];
                  
                  
              }];

              [alertController addAction:okAction];           // A
              [alertController addAction:cancelAction];       // B
           [weakSelf presentViewController:alertController animated:YES completion:nil];
           
          
         
       }
    };
    [self.signInApple handleAuthorizationAppleIDButtonPress];
}

- (void)bindPhoneAlertView
{
   
}



// 如果存在iCloud Keychain 凭证或者AppleID 凭证提示用户
- (void)perfomExistingAccount{
    // 封装Sign In with Apple 登录工具类，使用这个类时要把类对象设置为全局变量，或者直接把这个工具类做成单例，如果使用局部变量，和IAP支付工具类一样，会导致苹果回调不会执行
    self.signInApple = [[SignInApple alloc] init];
    self.signInApple.vc = self;
    __weak typeof(self) weakSelf = self;
    self.signInApple.SignInApple = ^(id  _Nonnull objc, NSString * _Nonnull Id) {
        NSString*status = [NSString stringWithFormat:@"%@",objc[@"status"]];
        typeof(weakSelf) __strong strongSelf = weakSelf;
       if ([status isEqualToString:@"0"]) {
           [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"firstlog"];
           lodModel*model = [lodModel mj_objectWithKeyValues:objc];
          if (model.userinfo.cus_name)
          {
              
              NSString *cusName = model.userinfo.cus_name;
              [getPeopleID getPeopletitle:cusName];
              
              [getPeopleID saveDefaultLoginAccount:model.userinfo.telphone];
              
          }
          
          if (model.userinfo.cus_password) {
              [getPeopleID saveDefaultLoginPassword:model.userinfo.cus_password];
          }
          
          
           [getPeopleID getPeoplePhoto:model.userinfo.photo];
          [getPeopleID getLoginType:@"appleLogin"];
          
          //存储登录时间
          NSDate* loginDate = [NSDate date];
          [getPeopleID saveLoginTime:loginDate];
          
           [getPeopleID getPeoplePhoto:model.userinfo.photo];
          [getPeopleID getPeopleID:model.userinfo.ID];
          
         
          [getPeopleID getPeopleIphoneNmber:model.userinfo.telphone];
          if (model.userinfo.account_type == 0) {
              [getPeopleID getpeopleLimitedAuthority:YES];
          }else
          {
              [getPeopleID getpeopleLimitedAuthority:NO];
          }
          
          [getPeopleID socialSate:1];
           //[GeTuiSdk bindAlias:[NSString stringWithFormat:@"kksh_%ld",model.userinfo.ID] andSequenceNum:[NSString stringWithFormat:@"%ld",model.userinfo.ID]];
           [[NSNotificationCenter defaultCenter] postNotificationName:KKSBLoginSuccessNotificationName object:nil userInfo:nil];
           
           
           [weakSelf.navigationController dismissViewControllerAnimated:YES completion:^{
               if (weakSelf.block) {
                   weakSelf.block(YES);
               }
           }];
          
          
          [CTAPIBaseManager GET3:LoginCountUrl params:@{} completionHandler:^(id  _Nonnull responseObject, NSError * _Nonnull error) {

          }];
       }else if ([status isEqualToString:@"1031"]){
            NSDictionary*userInfo = objc[@"userinfo"];
            NSString* kId = [NSString stringWithFormat:@"%@",userInfo[@"id"]];
//            NSString* photo = [NSString validBlankStr:userInfo[@"photo"]];
            NSString* cus_name = [EnercryTool decryptUseDES:[NSString validBlankStr:userInfo[@"cus_name"]] key:DESKEY] ? [EnercryTool decryptUseDES:[NSString validBlankStr:userInfo[@"cus_name"]] key:DESKEY] :@"";
         
           self->uid = Id;
           self->Id = kId.integerValue;
           self->accountName = cus_name;
           self->photoUrl = @"https://i.rensheju.com/userPhoto/defaultPhoto.png";
         
        // [getPeopleID]
         
        
         BPViewController *bpVC = [[BPViewController alloc]init];
         bpVC.UID = strongSelf->uid;
         bpVC.Id = [NSString stringWithFormat:@"%ld",(long)strongSelf->Id];
         bpVC.wxName = [NSString blankString:strongSelf->accountName] ? @"" :strongSelf->accountName;
         bpVC.wxPhotoUrl = strongSelf->photoUrl;
         bpVC.title = @"绑定手机号";
         [strongSelf.navigationController pushViewController:bpVC animated:YES];
           
       }
    };
    [self.signInApple perfomExistingAccountSetupFlows];
}


#pragma mark - loginBtnDelegate
- (void)loginBtnClickWith:(LoginView *)loginView
{
    
    
    CTLoginBtnType type  = CTLoginBtnTypeDefault;
    if (loginView == self.directlyLogin) {
        NSLog(@"一键登录");
        type = CTLoginBtnTypeDirectly;
    }else if (loginView == self.smsLogin){
        NSLog(@"短信登录");
        type = CTLoginBtnTypeSMS;
        //        SMSViewController *smsVC = [[SMSViewController alloc]init];
        //        [self.navigationController pushViewController:smsVC animated:YES];
    }else if (loginView == self.passwordLogin){
        NSLog(@"密码登录");
        type = CTLoginBtnTypePassword;
        //        PasswordLoginViewController *passwordVC  = [[PasswordLoginViewController alloc]init];
        //        [self.navigationController pushViewController:passwordVC animated:YES];
    }
    if ([self.delegate respondsToSelector:@selector(viewController:type:)]) {
        [self.delegate viewController:self type:type];
    }
}

#pragma mark - event response
//微信的第三方登入
-(void)tapWeChat{
    
    [self getUserInfoForPlatform:UMSocialPlatformType_WechatSession];
}


#pragma mark - private methods
//第三方登入
- (void)getUserInfoForPlatform:(UMSocialPlatformType)platformType
{
    
    [[UMSocialManager defaultManager] getUserInfoWithPlatform:platformType currentViewController:self completion:^(id result, NSError *error) {
        NSLog(@">>>>>wx>>result:%@, error:%@",result,error);
        
        if (error) {
             [SVProgressHUD showErrorWithStatus:@"微信授权失败!"];
            return;
        }
        
        UMSocialUserInfoResponse *resp = result;
        if(resp.uid ){
            if (!resp.name) {
                resp.name =@"";
            }
            if (!resp.iconurl) {
                resp.iconurl=@"";
            }
            
            //记录微信信息
            self->uid = resp.uid;
            self->photoUrl = resp.iconurl;
            self->accountName = resp.name;
            
            [self SenderSecondNetWorking:resp.uid andTelephone:nil andTelephonePassWord:nil andweixinId:resp.name andPicId:resp.iconurl];
        }
        // 第三方登录数据(为空表示平台未提供)
        // 授权数据
        NSLog(@" uid: %@", resp.uid);//uuid
        NSLog(@" openid: %@", resp.openid);
        NSLog(@" accessToken: %@", resp.accessToken);
        NSLog(@" refreshToken: %@", resp.refreshToken);
        NSLog(@" expiration: %@", resp.expiration);
        
        // 用户数据
        NSLog(@" name: %@", resp.name);
        NSLog(@" iconurl: %@", resp.iconurl);
        NSLog(@" gender: %@", resp.gender);
        
        // 第三方平台SDK原始数据
        NSLog(@" originalResponse: %@", resp.originalResponse);
    }];
}



#pragma mark -
- (void)managerDidRecvAuthResponse:(SendAuthResp *)response
{
    
}


#pragma mark - 网络请求
//曹妈妈
-(void)SenderSecondNetWorking:(NSString *)weixinStr andTelephone:(NSString*)telphone andTelephonePassWord:(NSString*)telephonePwd andweixinId:(NSString*)weixinId andPicId:(NSString *)picId{
    
    [KKLoadingAnimationView show];
    [logNetModel getLogMessage3:weixinStr andTelephone:telphone andLoginpassword:telephonePwd andUid:nil andl:2 andweixinId:weixinId andPicId:picId  completionHandle:^(lodModel *model, NSError *error) {
        [KKLoadingAnimationView dismiss];
        if (error) {
            [SVProgressHUD showErrorWithStatus:@"网络出错"];
            return;
        }
        
        
        if ([model.status isEqualToString:@"0"]) {
            
             [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"firstlog"];
            
            
            if (model.userinfo.cus_name)
            {
                
                NSString *cusName = model.userinfo.cus_name;
                [getPeopleID getPeopletitle:cusName];
                
                
            } else {
                [getPeopleID getPeopletitle:weixinId];
            }
            
            if (model.userinfo.cus_password) {
                [getPeopleID saveDefaultLoginPassword:model.userinfo.cus_password];
            }
            
            if ([model.userinfo.telphone containsString:@"undo"]) {
                NSString *str = [model.userinfo.telphone stringByReplacingOccurrencesOfString:@"undo" withString:@""];
                [getPeopleID saveDefaultLoginPassword:str];
            }else{
                [getPeopleID saveDefaultLoginAccount:model.userinfo.telphone];
            }
            
            
            
            if (!picId)  [getPeopleID getPeoplePhoto:model.userinfo.photo]; else [getPeopleID getPeoplePhoto:picId];
            [getPeopleID getLoginType:@"wxlogin"];
            
            //存储登录时间
            NSDate* loginDate = [NSDate date];
            [getPeopleID saveLoginTime:loginDate];
            
             [getPeopleID getPeoplePhoto:model.userinfo.photo];
            [getPeopleID getPeopleID:model.userinfo.ID];
            
           
            
            
            if ([model.userinfo.telphone containsString:@"undo"]) {
                NSString *str = [model.userinfo.telphone stringByReplacingOccurrencesOfString:@"undo" withString:@""];
                [getPeopleID getPeopleIphoneNmber:str];
            }else{
                [getPeopleID getPeopleIphoneNmber:model.userinfo.telphone];
            }
            
            
            if (model.userinfo.account_type == 0) {
                [getPeopleID getpeopleLimitedAuthority:YES];
            }else
            {
                [getPeopleID getpeopleLimitedAuthority:NO];
            }
            
            
            [getPeopleID socialSate:1];
            [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];
            
            
            WeakSelf
            [self.navigationController dismissViewControllerAnimated:YES completion:^{
                if (weakSelf.block) {
                    weakSelf.block(YES);
                }
            }];
            //初始化数据
            [[clickEvent instance] initData];
            [CTAPIBaseManager GET3:LoginCountUrl params:@{} completionHandler:^(id  _Nonnull responseObject, NSError * _Nonnull error) {

                          }];
            [NetworkRequest appLogin:0];
        }else if ([model.status isEqualToString:@"1031"]){
            
            if (model.userinfo) {
                self->Id = model.userinfo.ID;
            }
            @try {
                //此处写可能出现崩溃的代码
                //数组插入nil对象
                [self clGetTel];
            } @catch (NSException *exception) {
                //捕获到异常要执行的代码
                NSLog(@"exc == %@, 最后我弹了一个弹框说这样不合适",exception);
            } @finally {
                //不管能不能捕获到异常都会执行的方法
                NSLog(@"最后");
            }
            
        }else{
            //错误码提示
            codeSelected *code = [codeSelected MustTakeReturn:[model.status intValue]];
            [code returnCodeMethod];
        }
    }];

}


//获取手机号
- (void)clGetTel
{

    //创建一个ui配置对象
    SVSDKHyUIConfigure * uiConfigure = [[SVSDKHyUIConfigure alloc]init];
    //设置currentViewController，必传！请传入当前vc或视图顶层vc，可使用此vc调系统present测试是否可以present其他vc
    uiConfigure.currentViewController = self;
    //3.可选。设置一些定制化属性。eg. 开发者手动控制关闭授权页
    //uiConfigure.manualDismiss = @(YES);
    uiConfigure.navBarHidden = @(YES);
    uiConfigure.checkDefaultState=@(YES);//默认勾选协议
    // 自定义授权页(可选)
    self.uiMakerExample = [[CustomExample alloc]initWithTarget:self];
    //设置代理
    [SVSDKHyVerify setDelegate:self];
    [SVSDKHyVerify openAuthPageWithModel:uiConfigure openAuthPageListener:^(NSDictionary * _Nullable resultDic, NSError * _Nullable error) {
        NSLog(@"唤醒登录成功:%@,失败:%@",resultDic,error);
        if(error!=nil){
            //[Tools showMessage:@"一键登录失败!"];
            //[SVProgressHUD showInfoWithStatus:@"一键绑定失败,请通过短信验证码绑定手机号"];
            BPViewController *bpVC = [[BPViewController alloc]init];
            bpVC.UID = self->uid;
            bpVC.Id = [NSString stringWithFormat:@"%ld",(long)self->Id];
            bpVC.wxName = [NSString blankString:self->accountName] ? @"" :self->accountName;
            bpVC.wxPhotoUrl = self->photoUrl;
            bpVC.title = @"绑定手机号";
            [self.navigationController pushViewController:bpVC animated:YES];
        }
    } cancelAuthPageListener:^(NSDictionary * _Nullable resultDic, NSError * _Nullable error) {
        NSLog(@"取消登录:%@,失败:%@",resultDic,error);
    } oneKeyLoginListener:^(NSDictionary * _Nullable resultDic, NSError * _Nullable error) {
        if(error!=nil){
            //[Tools showMessage:@"一键登录失败!"];
            [SVProgressHUD showInfoWithStatus:@"一键绑定失败,请通过短信验证码绑定手机号"];
            BPViewController *bpVC = [[BPViewController alloc]init];
            bpVC.UID = self->uid;
            bpVC.Id = [NSString stringWithFormat:@"%ld",(long)self->Id];
            bpVC.wxName = [NSString blankString:self->accountName] ? @"" :self->accountName;
            bpVC.wxPhotoUrl = self->photoUrl;
            bpVC.title = @"绑定手机号";
            [self.navigationController pushViewController:bpVC animated:YES];
            return;
        }
        NSString *url = [NSString stringWithFormat:@"%@/socialsecurity/kankan/sharkBindTelephone",IPDIZHI];
        NSDictionary *dictNew =@{
                   @"appId":@"38b797dbbf6ec",
                   @"opToken":resultDic[@"opToken"],
                   @"token":resultDic[@"token"],
                   @"operator":resultDic[@"operator"],
                   @"loginBussinessType":@"10013",
                   @"timestamp":[NSNumber numberWithInteger:[self getNowTimeTimestamp3]].stringValue,
                   @"version":@"MYMOB",
                   @"loginType":@"2",
                   @"uid":self->uid,
                   @"authName":@"kkanface",
                   @"photoUrl":self->photoUrl,
                   @"accountName":self->accountName
                   };
        
        [NetworkRequest SBAuthPost:url Params:dictNew Success:^(id _Nonnull responseObject) {
            if ([responseObject isKindOfClass:[NSDictionary class]]) {
                NSString *status = [NSString stringWithFormat:@"%@",responseObject[@"status"]];
                if ([status isEqualToString:@"0"]) {
                    //设置登录标志
                    [UserDefault setBool:YES forKey:@"firstlog"];
                    [UserDefault synchronize];
                    NSDictionary *userinfo = responseObject[@"userinfo"];
                    //昵称
                    if (![Tools isBlankString:userinfo[@"cus_name"]]) {
                        [getPeopleID getPeopletitle:userinfo[@"cus_name"]];
                    }
                    //头像
                    if (![Tools isBlankString:userinfo[@"photo"]]) {
                        [getPeopleID getPeoplePhoto:userinfo[@"photo"]];
                    }
                    //存储登录类型
                     [getPeopleID getLoginType:@"wxlogin"];
                     //存储登录时间
                     NSDate* loginDate = [NSDate date];
                     [getPeopleID saveLoginTime:loginDate];
                    //userId
                    if ([userinfo[@"id"] isKindOfClass:[NSNumber class]]) {
                        NSNumber *Id = (NSNumber *)userinfo[@"id"];
                        [getPeopleID getPeopleID:Id.integerValue];
                    }
                    //存储默认登录手机号
                    if (![Tools isBlankString:userinfo[@"telphone"]]) {
                        [getPeopleID saveDefaultLoginAccount:userinfo[@"telphone"]];
                        NSString *tel=userinfo[@"telphone"];
                        if ([tel containsString:@"undo"]) {
                            tel = [tel stringByReplacingOccurrencesOfString:@"undo" withString:@""];
                        }
                        [getPeopleID getPeopleIphoneNmber:tel];
                    }
                    //存储默认密码
                    if (![Tools isBlankString:userinfo[@"cus_password"]]) {
                        [getPeopleID saveDefaultLoginPassword:userinfo[@"cus_password"]];
                    }
                    [getPeopleID socialSate:1];
                    //存储用户所在省份
                    NSString *provinceName = userinfo[@"provinceName"];
                    if ([Tools isBlankString:provinceName]){
                        NSString *province = [UserDefault objectForKey:@"locationProvince"];
                        if ([Tools isBlankString:province]) {
                            provinceName = @"上海市";
                        }else{
                            provinceName = province;
                        }
                    }
                    [getPeopleID getProvince:provinceName];
                    NSString *account_type = [NSString stringWithFormat:@"%@",userinfo[@"account_type"]];
                    if ([account_type isEqualToString:@"0"]) {
                        [getPeopleID getpeopleLimitedAuthority:YES];
                    }else
                    {
                        [getPeopleID getpeopleLimitedAuthority:NO];
                    }
                    //加密token使用
                    NSString* token = [Tools isBlankString:userinfo[@"token"]] ? @"" : userinfo[@"token"];
                    [UserDefault setObject:token forKey:@"loginToken"];
                    [[NSNotificationCenter defaultCenter] postNotificationName:KKSBLoginSuccessNotificationName object:nil userInfo:nil];
                    [CTAPIBaseManager GET3:LoginCountUrl params:@{} completionHandler:^(id  _Nonnull responseObject, NSError * _Nonnull error) {

                                             }];
                    WeakSelf
                    [self.navigationController dismissViewControllerAnimated:NO completion:^{
                        [self dismissViewControllerAnimated:YES completion:^{
                            if (weakSelf.block) {
                                weakSelf.block(YES);
                            }
                        }];
                    }];
                    return ;
                }else if ([status isEqualToString:@"10"]){
                    [self dismissViewControllerAnimated:YES completion:^{
                        NSDictionary *userinfo = responseObject[@"userinfo"];
                        if ([userinfo[@"id"] isKindOfClass:[NSNumber class]]){
                            NSNumber *Id1 = (NSNumber *)userinfo[@"id"];
                            self->Id = Id1.integerValue;
                        }
                        [SVProgressHUD showInfoWithStatus:@"该手机号已绑定,请绑定别的手机号"];
                        BPViewController *bpVC = [[BPViewController alloc]init];
                        bpVC.UID = self->uid;
                        bpVC.Id = [NSString stringWithFormat:@"%ld",(long)self->Id];
                        bpVC.wxName = [NSString blankString:self->accountName] ? @"" :self->accountName;
                        bpVC.wxPhotoUrl = self->photoUrl;
                        bpVC.title = @"绑定手机号";
                        [self.navigationController pushViewController:bpVC animated:YES];
                    }];
                    return;
                }
            }
            [self dismissViewControllerAnimated:YES completion:^{
                [SVProgressHUD showInfoWithStatus:@"请先绑定手机号"];
                BPViewController *bpVC = [[BPViewController alloc]init];
                bpVC.UID = self->uid;
                bpVC.Id = [NSString stringWithFormat:@"%ld",(long)self->Id];
                bpVC.wxName = [NSString blankString:self->accountName] ? @"" :self->accountName;
                bpVC.wxPhotoUrl = self->photoUrl;
                bpVC.title = @"绑定手机号";
                [self.navigationController pushViewController:bpVC animated:YES];
            }];
        } Failure:^(NSError* error) {
           
        }];
    }];
    
}

#pragma mark - 自定义授权页按钮点击事件
// 点击自定义返回
- (void)customBackAction:(UIButton *)button{
    //关闭登录视图
    [SVSDKHyVerify finishLoginVcAnimated:YES Completion:^{
        NSLog(@"点击自定义返回...");
    }];
}

// 自定义授权页上微信按钮点击事件
- (void)weixinLoginAction:(UIButton *)button{
    //关闭登录视图
//    [SVSDKHyVerify finishLoginVcAnimated:YES Completion:^{
//        NSLog(@"点击微信登录...");
//    }];
    [self.view bringSubviewToFront:self.wxVC.view];
    [self.navigationController dismissViewControllerAnimated:YES completion:nil];
}

// 自定义授权页上短信登录按钮点击事件
- (void)smsLoginAction:(UIButton *)button{
//    [SVSDKHyVerify finishLoginVcAnimated:YES Completion:^{
//        NSLog(@"点击短信登录...");
//    }];
    [self.view bringSubviewToFront:self.smsVC.view];
    [self.navigationController dismissViewControllerAnimated:YES completion:nil];
}


// 自定义授权页上账号按钮点击事件
- (void)usernameLoginAction:(UIButton *)button{
//    [SVSDKHyVerify finishLoginVcAnimated:YES Completion:^{
//        NSLog(@"点击密码登录...");
//    }];
    [self.view bringSubviewToFront:self.passwordVC.view];
    [self.navigationController dismissViewControllerAnimated:YES completion:nil];
}

- (WXLoginViewController *)wxVC
{
    if (!_wxVC) {
        _wxVC = [WXLoginViewController new];
        _wxVC.delegate = self;
        _wxVC.block = self.block;
    }
    return _wxVC;
}
- (SMSLoginViewController *)smsVC
{
    if (!_smsVC) {
        _smsVC = [SMSLoginViewController new];
        _smsVC.delegate =self;
        _smsVC.block = self.block;
    }
    return _smsVC;
}
- (PasswordLoginViewController *)passwordVC
{
    if (!_passwordVC) {
        _passwordVC = [PasswordLoginViewController new];
        _passwordVC.delegate = self;
        _passwordVC.block = self.block;
    }
    return _passwordVC;
}


#pragma mark - SVSDKVerifyDelegate
-(void)svVerifyAuthPageDealloc{
    //授权页释放
    NSLog(@"%s",__func__);
    
}
-(void)svVerifyAuthPageViewWillTransition:(UIViewController *)authVC toSize:(CGSize)size withTransitionCoordinator:(id<UIViewControllerTransitionCoordinator>)coordinator userInfo:(SVSDKHyProtocolUserInfo *)userInfo{
    //(可选)此处可以设置横竖屏切换
    if ([self.uiMakerExample respondsToSelector:@selector(authPageViewWillTransition:toSize:withTransitionCoordinator:userInfo:)]) {
        [self.uiMakerExample authPageViewWillTransition:authVC toSize:size withTransitionCoordinator:coordinator userInfo:userInfo];
    }
}
-(void)svVerifyAuthPageWillPresent:(UIViewController *)authVC userInfo:(SVSDKHyProtocolUserInfo *)userInfo{
    //(可选)此处可以自定义转场动画
    authVC.navigationController.transitioningDelegate = self.uiMakerExample;
}

-(void)svVerifyAuthPageViewDidLoad:(UIViewController *)authVC userInfo:(SVSDKHyProtocolUserInfo *)userInfo{
    
    //(可选)记录当前的授权页vc对象，请使用❗️弱引用
    self.authPageVc = authVC;
    
    //⚠️由于本demo工程有多个UI样式，故将自定义示例代码移到了对应的uiMakerExample中，实际可直接在此处设置
    
    //自定义授权页UI
    [self.uiMakerExample setupAuthPageCustomStyle:authVC userInfo:userInfo];
}


- (void)setupUI
{
    //图标
    [self.imgView_topIcon mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.view.mas_centerX);
        make.top.offset(104 * HEIGHTRADIU);
        make.width.offset(70*WIDTHRADIU);
        make.height.offset(70*WIDTHRADIU);
    }];
    
    //title
    
    CGSize topSize = [self.lab_title.text sizeWithAttributes:[NSDictionary dictionaryWithObjectsAndKeys:[UIFont boldSystemFontOfSize:20 * WIDTHRADIU],NSFontAttributeName, nil]];
    CGFloat topH = topSize.height;
    
    [self.lab_title mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self -> _imgView_topIcon.mas_bottom).offset(24*WIDTHRADIU);
        make.left.right.offset(0);
        make.height.offset(topH);
    }];
    
    
    //wxBtn
    [self.btn_WXLogin mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self -> _lab_title.mas_bottom).offset(46*WIDTHRADIU);
        make.centerX.equalTo(self.view.mas_centerX);
        make.width.offset(315 * WIDTHRADIU);
        make.height.offset(45 * WIDTHRADIU);
    }];
    
     // 使用系统提供的按钮，要注意不支持系统版本的处理
     if (@available(iOS 13.0, *)) {
         // Sign In With Apple Button
         ASAuthorizationAppleIDButton *appleIDBtn = [ASAuthorizationAppleIDButton buttonWithType:ASAuthorizationAppleIDButtonTypeDefault style:ASAuthorizationAppleIDButtonStyleWhiteOutline];
         //appleIDBtn.frame = CGRectMake(30 * WIDTHRADIU, self.view.bounds.size.height - 180, self.view.bounds.size.width - 60, 100);
         
         appleIDBtn.cornerRadius = 4.f * WIDTHRADIU;
         [appleIDBtn addTarget:self action:@selector(didAppleIDBtnClicked) forControlEvents:UIControlEventTouchUpInside];
         [self.view addSubview:appleIDBtn];
         
         [appleIDBtn mas_makeConstraints:^(MASConstraintMaker *make) {
             make.top.equalTo(self.btn_WXLogin.mas_bottom).offset(20 * WIDTHRADIU);
             make.centerX.equalTo(self.btn_WXLogin);
             make.width.offset(315 * WIDTHRADIU);
             make.height.offset(45 * WIDTHRADIU);
         }];
         
     }
    
    
    [self.smsLogin mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(self.view.mas_bottom).offset(-40 * WIDTHRADIU);
        make.centerX.equalTo(self.view.mas_centerX);
        make.height.offset(72 * WIDTHRADIU);
        make.width.offset(60 * WIDTHRADIU);
    }];
    
    
    
    [self.directlyLogin mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(self.smsLogin.mas_centerY);
        make.right.equalTo(self.smsLogin.mas_left).offset(-44* WIDTHRADIU);
        make.height.equalTo(self.smsLogin.mas_height);
        make.width.equalTo(self.smsLogin.mas_width);
    }];
    [self.passwordLogin mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(self.smsLogin.mas_centerY);
        make.left.equalTo(self.smsLogin.mas_right).offset(44* WIDTHRADIU);
        make.height.equalTo(self.smsLogin.mas_height);
        make.width.equalTo(self.smsLogin.mas_width);
    }];
    
    CGSize middleSize = [self.middleLab.text sizeWithAttributes:[NSDictionary dictionaryWithObjectsAndKeys:[UIFont systemFontOfSize:17],NSFontAttributeName, nil]];
    CGFloat middleH = middleSize.height;
    [self.middleLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(self -> _smsLogin.mas_top).offset(-35*WIDTHRADIU);
        make.centerX.equalTo(self.view.mas_centerX);
        make.height.offset(middleH);
    }];
    [self.middleLab setContentCompressionResistancePriority:UILayoutPriorityDefaultHigh forAxis:UILayoutConstraintAxisHorizontal];
    [self.leftLine mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(self.middleLab.mas_centerY);
        make.left.equalTo(self.view.mas_left).offset(25 * WIDTHRADIU);
        make.right.equalTo(self -> _middleLab.mas_left).offset(-16);
        make.height.offset(0.5);
    }];
    [self.rightLine mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(self.middleLab.mas_centerY);
        make.left.equalTo(self -> _middleLab.mas_right).offset(16);
        make.right.equalTo(self.view.mas_right).offset(-25 * WIDTHRADIU);
        make.height.offset(0.5);
    }];
}
#pragma mark - getters and setters

-(NSInteger )getNowTimeTimestamp3{
    
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init] ;
    
    [formatter setDateStyle:NSDateFormatterMediumStyle];
    
    [formatter setTimeStyle:NSDateFormatterShortStyle];
    
    [formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss SSS"]; // ----------设置你想要的格式,hh与HH的区别:分别表示12小时制,24小时制
    
    //设置时区,这个对于时间的处理有时很重要
    
    NSTimeZone* timeZone = [NSTimeZone timeZoneWithName:@"Asia/Beijing"];
    
    [formatter setTimeZone:timeZone];
    
    NSDate *datenow = [NSDate date];//现在时间,你可以输出来看下是什么格式
    
    NSInteger timeSp = [datenow timeIntervalSince1970]*1000;
    
    return timeSp;
}

//- (NSDictionary *)getsharkBindTelephoneParams
//{
//    NSDictionary *params = @{
//        @"Id":[NSNumber numberWithInt:Id],
//        @"uid":uid,
//        @"loginType":@"2",
//        @"photoUrl":photoUrl,
//        @"accountName":accountName,
//        @"appId":appId,
//        @"accessToken":accessToken,
//        @"telecom":[NSString blankString:telecom] ? @"" :telecom,
//        @"timestamp":[NSString blankString:timestamp] ? @"" :timestamp,
//        @"randoms":[NSString blankString:randoms] ? @"" :randoms,
//        @"version":[NSString blankString:version] ? @"" :version,
//        @"device":[NSString blankString:device] ? @"" :device,
//        @"sign":[NSString blankString:sign] ? @"" :sign,
//        @"loginBussinessType":@"10011",
//        @"mobileType":@"",
//        @"autoCode":@"",
//        @"platForm":@"",
//    };
//
//    return params;
//}

- (NSDictionary *)getsharkBindTelephoneParams
{
    NSDictionary *params = @{
       // @"Id":[NSNumber numberWithInt:Id],
        @"uid":uid,
        @"loginType":@"2",
        @"photoUrl":photoUrl,
        @"accountName":accountName,
        @"appId":cl_SDK_APPID,
        @"accessToken":accessToken,
       // @"telecom":[NSString blankString:telecom] ? @"" :telecom,
        @"timestamp":[NSNumber numberWithInteger:[self getNowTimeTimestamp3]].stringValue,
       // @"randoms":[NSString blankString:randoms] ? @"" :randoms,
        @"version":@"CL231",
        //@"device":[NSString blankString:device] ? @"" :device,
        //@"sign":[NSString blankString:sign] ? @"" :sign,
        @"loginBussinessType":@"10013",
        @"mobileType":@"",
        //@"autoCode":@"",
       // @"platForm":@"",
    };
    
    return params;
}

- (UIImageView *)imgView_topIcon
{
    if (!_imgView_topIcon) {
        ;
        UIImage *image = [UIImage imageNamed:@"login_icon"];
        _imgView_topIcon = [[UIImageView alloc]init];
        _imgView_topIcon.image = image;
        
    }
    return _imgView_topIcon;
}

- (UILabel *)lab_title
{
    if (!_lab_title) {
        _lab_title = [[UILabel alloc]init];
        _lab_title.textColor = RGBACOLOR(77, 77, 77, 1.0);
        _lab_title.text = @"看看生活-让领钱更简单";
        _lab_title.textAlignment = NSTextAlignmentCenter;
        //_lab_title.font = [UIFont systemFontOfSize:20*WIDTHRADIU];
        _lab_title.font = [UIFont boldSystemFontOfSize:20 * WIDTHRADIU];
    }
    return _lab_title;
}

- (UIButton *)btn_WXLogin
{
    if (!_btn_WXLogin) {
        _btn_WXLogin = [UIButton buttonWithType:UIButtonTypeCustom];
        [_btn_WXLogin setImage:[UIImage imageNamed:@"login_button_WeChat_normal"] forState:UIControlStateNormal];
        [_btn_WXLogin setTitle:@"微信一键登录" forState:UIControlStateNormal];
        [_btn_WXLogin.titleLabel setFont:[UIFont systemFontOfSize:17*WIDTHRADIU]];
        [_btn_WXLogin setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [_btn_WXLogin setBackgroundColor:RGBCOLOR(22, 124, 205)];
        _btn_WXLogin.layer.cornerRadius = 5*WIDTHRADIU;
        [_btn_WXLogin layoutButtonWithEdgeInsetsStyle:GLButtonEdgeInsetsStyleLeft imageTitleSpace:8*WIDTHRADIU];
        [_btn_WXLogin addTarget:self action:@selector(tapWeChat) forControlEvents:UIControlEventTouchUpInside];
    }
    return _btn_WXLogin;
}

- (LoginView *)directlyLogin
{
    if (!_directlyLogin) {
        _directlyLogin = [[LoginView alloc]initWithTitle:@"一键登录" imageName:@"login_otherlogin_One-click_normal"];
        _directlyLogin.delegate = self;
    }
    return _directlyLogin;
}

- (LoginView *)smsLogin
{
    if (!_smsLogin) {
        _smsLogin = [[LoginView alloc]initWithTitle:@"短信登录" imageName:@"login_otherlogin_SMS_normal"];
        _smsLogin.delegate = self;
    }
    return _smsLogin;
}

- (LoginView *)passwordLogin
{
    if (!_passwordLogin) {
        _passwordLogin = [[LoginView alloc]initWithTitle:@"密码登录" imageName:@"login_otherlogin_password_normal"];
        _passwordLogin.delegate = self;
    }
    return _passwordLogin;
}

- (UIView *)leftLine
{
    if (!_leftLine) {
        _leftLine = [[UIView alloc]init];
        _leftLine.backgroundColor = RGBCOLOR(204, 204, 204);
    }
    return _leftLine;
}

- (UILabel *)middleLab
{
    if (!_middleLab) {
        _middleLab = [[UILabel alloc]init];
        _middleLab.textColor = RGBACOLOR(153, 153, 153, 1.0);
        _middleLab.text = @"其他登录方式";
        _middleLab.textAlignment = NSTextAlignmentCenter;
        _middleLab.font = [UIFont systemFontOfSize:13*WIDTHRADIU];
    }
    return _middleLab;
}

- (UIView *)rightLine
{
    if (!_rightLine) {
        _rightLine = [[UIView alloc]init];
        _rightLine.backgroundColor = RGBCOLOR(204, 204, 204);
    }
    return _rightLine;
}
/*
#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
