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

#import "LoginVC.h"
#import "loginProtocol.h"

#import "WXLoginViewController.h"
#import "SMSLoginViewController.h"
#import "PasswordLoginViewController.h"
#import "CTAPIBaseManager.h"

#import "Constants.h"

#import "CustomExample.h"
#import "LoginView.h"
//mob一键登录
#import <SecVerify/SVSDKHyVerify.h>


@interface LoginVC ()<LoginClickDelegate,loginBtnDelegate,SVSDKVerifyDelegate>

@property (nonatomic, strong)WXLoginViewController *wxVC;

@property (nonatomic, strong)SMSLoginViewController *smsVC;

@property (nonatomic, strong)PasswordLoginViewController *passwordVC;

@property (nonatomic, strong)UIView *customView;

@property (nonatomic, strong) LoginView *wxLogin;

@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;

@end

@implementation LoginVC
#pragma mark - life cycle
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self.navigationController.navigationBar setBackgroundImage:[[UIImage alloc]init] forBarMetrics:UIBarMetricsDefault];
    
    [self.navigationController.navigationBar setShadowImage:[[UIImage alloc]init]];
    
    self.view.backgroundColor = [UIColor whiteColor];
    
    UIBarButtonItem *backItem = [[UIBarButtonItem alloc] initWithImage:[[UIImage imageNamed:@"back"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal]  style:UIBarButtonItemStylePlain target:self action:@selector(back)];
    self.navigationItem.leftBarButtonItem = backItem;
    
    
    
    [self addChildViewController:self.wxVC];
    [self addChildViewController:self.smsVC];
    [self addChildViewController:self.passwordVC];
    [self fitFrameForChildViewController:self.wxVC];
    [self fitFrameForChildViewController:self.smsVC];
    [self fitFrameForChildViewController:self.passwordVC];
    [self.view addSubview:self.wxVC.view];
    [self.view addSubview:self.smsVC.view];
    [self.view addSubview:self.passwordVC.view];
    [self.view bringSubviewToFront:self.wxVC.view];
    
    
    //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{
            //失败
            NSLog(@"mob预取号失败:%@",error);
        }
    }];
    
    AppDelegate *delegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
    
    delegate.loginShow = YES;
    
}
- (void)dealloc
{
    NSLog(@"LoginVC已销毁");
    AppDelegate *delegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
    
    delegate.loginShow = NO;
}
#pragma mark - LoginClickDelegate
- (void)viewController:(UIViewController *)vc type:(CTLoginBtnType)type
{
    switch (type) {
        case CTLoginBtnTypeWX:
            [self.view bringSubviewToFront:self.wxVC.view];
            break;
        case CTLoginBtnTypeSMS:
            [self.view bringSubviewToFront:self.smsVC.view];
            break;
        case CTLoginBtnTypePassword:
            [self.view bringSubviewToFront:self.passwordVC.view];
            break;
        case CTLoginBtnTypeDirectly:
            
            //闪验
            [self clLogin];
           
            break;
            
        default:
            break;
    }
}
//弹框提示
- (void)showAlert:(NSString *)title message:(NSString *)message{
    dispatch_async(dispatch_get_main_queue(), ^{
        UIAlertController* alert = [UIAlertController alertControllerWithTitle:title
                                                                       message:message
                                                                preferredStyle:UIAlertControllerStyleAlert];
        
        UIAlertAction* defaultAction = [UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleDefault
                                                              handler:^(UIAlertAction * action) {
                                                              }];
        [alert addAction:defaultAction];
        [self presentViewController:alert animated:YES completion:nil];
    });
}

- (void)clLogin{
//    //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{
//            //失败
//            NSLog(@"mob预取号失败:%@",error);
//        }
//    }];

    
    //创建一个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];
    //[CustomExample setPrivacySettingExample:uiConfigure];
    [SVSDKHyVerify openAuthPageWithModel:uiConfigure openAuthPageListener:^(NSDictionary * _Nullable resultDic, NSError * _Nullable error) {
        NSLog(@"唤醒登录:%@,失败:%@",resultDic,error);
        if(error!=nil){
            NSString *msg=[NSString stringWithFormat:@"%@",error.userInfo ? error.userInfo.description : error.domain];
            [self showAlert:@"一键登录失败" message:@"请检查蜂窝网络是否打开或SIM卡状态"];
        }
    } cancelAuthPageListener:^(NSDictionary * _Nullable resultDic, NSError * _Nullable error) {
        NSLog(@"取消登录:%@,失败:%@",resultDic,error);
    } oneKeyLoginListener:^(NSDictionary * _Nullable resultDic, NSError * _Nullable error) {
        NSLog(@"一键登录成功:%@,失败:%@",resultDic,error);
        if(error!=nil){
            NSString *msg=[NSString stringWithFormat:@"%@",error.userInfo ? error.userInfo.description : error.domain];
            [self showAlert:@"一键登录失败" message:msg];
            return;
        }
        NSString *path=[IPDIZHI stringByAppendingString:@"/socialsecurity/kankan/sharkLogin"];
        //NSString *path=@"http://172.16.10.215:8081/socialsecurity/kankan/sharkLogin";
        NSDictionary *dictNew =nil;
        dictNew =@{
                   @"appId":[EnercryTool encryptUseDES:@"38b797dbbf6ec" key:DESKEY],
                   @"opToken":resultDic[@"opToken"],
                   @"token":resultDic[@"token"],
                   @"operator":resultDic[@"operator"],
                   @"loginBussinessType":@"10013",
                   @"timestamp":[NSNumber numberWithInteger:[self getNowTimeTimestamp3]].stringValue,
                   @"version":@"MYMOB"
                   };
       
        [BaseNetManager POST4:path parameters:dictNew completionHandler:^(id responseObj, NSError *error) {
            if (responseObj) {
                if ([responseObj isKindOfClass:[NSData class]]) {
                    NSDictionary* dic = [NSJSONSerialization JSONObjectWithData:responseObj options:kNilOptions error:nil];
                    NSLog(@"responseObj123%@",dic);
                }
                logModel_2 *model=  [logModel_2 mj_objectWithKeyValues:responseObj];
                if ([model.code isEqualToString:@"0"]) {
                    NSLog(@"123%@",model.code);
                    //判断账号是否登入时候使用
                    [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"firstlog"];
                    //登录方式
                    [getPeopleID getLoginType:@"directlylogin"];
                    //存储登录时间
                    NSDate* loginDate = [NSDate date];
                    [getPeopleID saveLoginTime:loginDate];
                    
                    //保存用户昵称
                    if (![Tools isBlankString:model.result.cus_name]) {
                        [getPeopleID getPeopletitle:model.result.cus_name];
                    }
                    //存储头像
                    NSString *userIcon = nil;
                    if (![Tools isBlankString:model.result.photo]) {
                        userIcon = model.result.photo;
                    }else{
                        userIcon = @"https://i.rensheju.com/userPhoto/defaultPhoto.png";
                    }
                    [getPeopleID getPeoplePhoto:userIcon];
                    
                    
                    //userId
                    [getPeopleID getPeopleID:model.result.ID];
                    
                    
                    //存储手机号
                    NSString *userBindTel = model.result.telphone;
                    if (![Tools isBlankString:userBindTel]) {
                        if ([model.result.telphone containsString:@"undo"]) {
                            userBindTel = [model.result.telphone stringByReplacingOccurrencesOfString:@"undo" withString:@""];
                        }
                        
                        [getPeopleID getPeopleIphoneNmber:userBindTel];
                    }
                    
                    //存储默认登录手机号
                    if (![Tools isBlankString:model.result.telphone]) {
                        [getPeopleID saveDefaultLoginAccount:model.result.telphone];
                    }
                    
                    //存储默认登录密码
                    if (![Tools isBlankString:model.result.cus_password]) {
                        [getPeopleID saveDefaultLoginPassword:model.result.cus_password];
                    }
                    
                    
                    //存储用户所在省份
                    NSString *provinceName = model.result.provinceName;
                    if ([Tools isBlankString:provinceName]) {
                        NSString *province = [UserDefault objectForKey:@"locationProvince"];
                        if ([Tools isBlankString:province]) {
                            [getPeopleID getProvince:@"上海市"];
                        }else{
                            [getPeopleID getProvince:province];
                        }
                    }else{
                        [getPeopleID getProvince:provinceName];
                    }
                    
                    
                    //判断是否是授权用户
                    if (model.result.account_type == 0) {
                        
                        [getPeopleID getpeopleLimitedAuthority:YES];
                    }else
                    {
                        [getPeopleID getpeopleLimitedAuthority:NO];
                    }
                    
                    
                    
                    [UserDefault setObject:model.result.token forKey:@"loginToken"];
                    [getPeopleID socialSate:1];
                    //初始化数据
                    [[clickEvent instance] initData];
                    WeakSelf
                    [self.navigationController dismissViewControllerAnimated:NO completion:^{
                        [self dismissViewControllerAnimated:YES completion:^{
                            
                            if (weakSelf.block) {
                                weakSelf.block(YES);
                            }
                            
                        }];
                    }];
                   
                    [[NSNotificationCenter defaultCenter] postNotificationName:KKSBLoginSuccessNotificationName object:nil userInfo:nil];
                    
                    [CTAPIBaseManager GET3:LoginCountUrl params:@{} completionHandler:^(id  _Nonnull responseObject, NSError * _Nonnull error) {

                    }];
                    
                }else{
                    //雷俊博代码

                    codeSelected *code = [codeSelected MustTakeReturn:[model.code intValue]];
                    [code returnCodeMethod];
                    
                }
            }
            if (error) {
                NSLog(@"登录失败:错误:%@",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];
}



#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];
}

#pragma mark - loginBtnDelegate
- (void)loginBtnClickWith:(LoginView *)loginView
{
//    WeakSelf
    CTLoginBtnType type  = CTLoginBtnTypeDefault;
    if (loginView == self.wxLogin) {
        NSLog(@"一键登录");
        type = CTLoginBtnTypeWX;
        
        [self.view bringSubviewToFront:self.wxVC.view];
        [self.navigationController dismissViewControllerAnimated:YES completion:nil];
        
    }else if (loginView == self.smsLogin){
        NSLog(@"短信登录");
        type = CTLoginBtnTypeSMS;
        //        SMSViewController *smsVC = [[SMSViewController alloc]init];
        //        [self.navigationController pushViewController:smsVC animated:YES];
        [self.view bringSubviewToFront:self.smsVC.view];
        [self.navigationController dismissViewControllerAnimated:YES completion:nil];
    }else if (loginView == self.passwordLogin){
        NSLog(@"密码登录");
        type = CTLoginBtnTypePassword;
        //        PasswordLoginViewController *passwordVC  = [[PasswordLoginViewController alloc]init];
        //        [self.navigationController pushViewController:passwordVC animated:YES];
        [self.view bringSubviewToFront:self.passwordVC.view];
        [self.navigationController dismissViewControllerAnimated:YES completion:nil];
        
    }
   
}


#pragma mark - event response
- (void)back
{
    [self.view endEditing:YES];
    NSLog(@"返回了");
    //用户主动不登录,需要把推送的内容清除
    [[NSUserDefaults standardUserDefaults]setObject:nil forKey:@"mob_pushUrl"];
    [[NSUserDefaults standardUserDefaults]setObject:nil forKey:@"mob_pushType"];
    //再返回
    [self.navigationController dismissViewControllerAnimated:YES completion:nil];
}


#pragma mark - private methods
#pragma mark 字典转化字符串
-(NSString*)dictionaryToJson:(NSDictionary *)dic
{
    NSError *parseError = nil;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dic options:NSJSONWritingPrettyPrinted error:&parseError];
    
    return [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
}
- (void)fitFrameForChildViewController:(UIViewController *)chileViewController{
    
    chileViewController.view.frame = self.view.bounds;
    
}

-(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;
}


#pragma mark - getters and setters
- (void)setBlock:(LoginVCSuccessBlock)block
{
    self.wxVC.block = block;
    self.smsVC.block = block;
    self.passwordVC.block = block;
}
- (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;
}

- (UIView *)customView
{
    if (!_customView) {
        _customView = [[UIView alloc]init];
        _customView.backgroundColor = [UIColor whiteColor];
        
        [_customView addSubview:self.wxLogin];
        [_customView addSubview:self.smsLogin];
        [_customView addSubview:self.passwordLogin];
           
        [_customView addSubview:self.leftLine];
        [_customView addSubview:self.middleLab];
        [_customView addSubview:self.rightLine];
        
        [self.smsLogin mas_makeConstraints:^(MASConstraintMaker *make) {
            make.bottom.equalTo(self->_customView.mas_bottom).offset(-40 * WIDTHRADIU);
            make.centerX.equalTo(self->_customView.mas_centerX);
            make.height.offset(72 * WIDTHRADIU);
            make.width.offset(60 * WIDTHRADIU);
        }];
        
        
        
        [self.wxLogin 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->_customView.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->_customView.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->_customView.mas_right).offset(-25 * WIDTHRADIU);
              make.height.offset(0.5);
          }];
        
    }
    return _customView;
}

- (LoginView *)wxLogin
{
    if (!_wxLogin) {
        _wxLogin = [[LoginView alloc]initWithTitle:@"微信登录" imageName:@"login_otherlogin_WeChat_normal-1"];
        _wxLogin.delegate = self;
    }
    return _wxLogin;
}

- (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
