//
//  KKUserAuthViewController.m
//  Open
//
//  Created by 雷俊博 on 2021/1/21.
//  Copyright © 2021 黄江涛 . All rights reserved.
//

#import "KKUserAuthViewController.h"
#import "SCCaptureCameraController.h"
#import "KKIDKeyboardView.h"
#import "FaceImageModel.h"
#import "NSString+Timestamp.h"
#import "DDSBCardViewController.h"
#import "KKUserIdentifyViewController.h"
#import "DistrictAuthenticationPersonalInfoController.h"
#import "KKUserAuthSuccessViewController.h"

#import "TestViewController.h"

@interface KKUserAuthViewController ()<SCNavigationControllerDelegate,KKIDKeyboardViewDelegate,passImagesDelegate>

@property (nonatomic, strong)UITextField *nameText;

@property (nonatomic, strong)UITextField *idText;

@property(nonatomic,strong)KKIDKeyboardView *keyboardView;

@end

@implementation KKUserAuthViewController
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    [self.navigationController setNavigationBarHidden:YES animated:animated];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor whiteColor];
    [self configNav];
    [self setUpUI];
    
//    if (self.nameTT) {
//        self.nameText.text = self.nameTT;
//    }
//
//    if (self.numTT) {
//        self.idText.text = [NSString stringWithFormat:@"%@ %@ %@ %@",[self.numTT substringToIndex:6], [self.numTT substringWithRange:NSMakeRange(6, 4)],[self.numTT substringWithRange:NSMakeRange(10, 4)],[self.numTT substringWithRange:NSMakeRange(14, 4)]];
//    }
    
    
    
    
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(jiePing) name:UIApplicationUserDidTakeScreenshotNotification  object:nil];
}

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIApplicationUserDidTakeScreenshotNotification object:nil];
}


- (void)configNav
{
   UIView*nav = [[UIView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, cl_kNavigationBarHeight)];
    nav.backgroundColor = [UIColor colorWithHex:0x086ed7];
    [self.view addSubview:nav];
    
    UIButton*backBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [backBtn setTitle:@"返回" forState:UIControlStateNormal];
    [backBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [backBtn setImage:[UIImage imageNamed:@"返回"] forState:UIControlStateNormal];
    [backBtn layoutButtonWithEdgeInsetsStyle:GLButtonEdgeInsetsStyleLeft imageTitleSpace:4];
    [backBtn addTarget:self action:@selector(backClick) forControlEvents:UIControlEventTouchUpInside];
    [nav addSubview:backBtn];
    
    [backBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.offset(0);
        make.top.offset(cl_kStatusBarHeight);
        make.width.offset(80);
        make.height.offset(44);
    }];
    
    UILabel*titleLabel = [[UILabel alloc]init];
    titleLabel.textColor = [UIColor whiteColor];
    titleLabel.textAlignment = NSTextAlignmentCenter;
    titleLabel.text = self.title;
    titleLabel.font = [UIFont boldSystemFontOfSize:17];
    [nav addSubview:titleLabel];
    
    [titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.offset(0);
        make.top.offset(cl_kStatusBarHeight);
        make.width.offset(80);
        make.height.offset(44);
    }];
    
    
}

- (void)setUpUI {
    
    //顶部图片
    CGFloat imageSizeScale = 112/375.0;
    UIImageView *topBg = [[UIImageView alloc]initWithFrame:CGRectMake(0, cl_kNavigationBarHeight, ScreenWidth, ScreenWidth*imageSizeScale)];
    topBg.image = [UIImage imageNamed:@"auth_bg"];
    [self.view addSubview:topBg];
    //title
    
    
     NSString* number =[UserDefault objectForKey:@"certRealNameCount"];
    NSString *title =  [NSString stringWithFormat:@"为规范补贴发放秩序,避免冒领错领\n账户实名认证后,每天认证人数可升级到%@人",number];
//    if (self.type == KKUserAuthFromVCTypeDDSBCard) {
//        title = @"为保证电子社保卡开通安全性\n请进行实名认证!";
//    }else if (self.type == KKUserAuthFromVCTypeSBAuth) {
//        title = @"为规范养老金发放秩序,避免冒领错领,账户实名认证后,每天认证人数可升级到20人";
//    }else if (self.type == KKUserAuthFromVCTypeBuTie) {
//        title = @"为规范养老金发放秩序,避免冒领错领,账户实名认证后,每天认证人数可升级到20人";
//    }else if (self.type == KKUserAuthFromVCTypeYouFu) {
//        title = @"为规范养老金发放秩序,避免冒领错领,账户实名认证后,每天认证人数可升级到20人";
//    }
    UILabel *lb_title = [UILabel new];
    lb_title.attributedText = [self getAttributedStringWithString:title lineSpace:12* WIDTHRADIU kern:0.5];
    lb_title.textColor = [UIColor whiteColor];
    lb_title.numberOfLines = 0;
    [topBg addSubview:lb_title];
    
    [lb_title mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.offset(30 * WIDTHRADIU);
        make.centerX.equalTo(topBg);
        make.left.offset(10 * WIDTHRADIU);
        make.right.offset(-10 * WIDTHRADIU);
    }];
    
    
    //姓名
    UIImageView*nameImg = [[UIImageView alloc]initWithFrame:CGRectMake(11 * WIDTHRADIU, CGRectGetMaxY(topBg.frame) + 23 * WIDTHRADIU, ScreenWidth - 22 * WIDTHRADIU, (ScreenWidth - 22 * WIDTHRADIU) * 58/353.0)];
    nameImg.image = [UIImage imageNamed:@"社保认证姓名"];
    [self.view addSubview:nameImg];
//    self.nameImg = nameImg;
    
    UITextField*tf_name = [[UITextField alloc]init];
    tf_name.textColor = [UIColor colorWithHex:0x4d4d4d];
    tf_name.font = [UIFont systemFontOfSize:15* WIDTHRADIU];
    tf_name.placeholder = @"请输入姓名";
    //                         tf_name.delegate = self;
    self.nameText = tf_name;
    [self.view addSubview:tf_name];
    
    [tf_name mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(nameImg);
        make.right.equalTo(nameImg.mas_right).offset(-20 * WIDTHRADIU);
        make.left.equalTo(nameImg.mas_left).offset(85 * WIDTHRADIU);
        make.height.equalTo(nameImg.mas_height).multipliedBy(0.85);
    }];
    
    //身份证号码
    UIImageView*idImg = [[UIImageView alloc]init];
    idImg.image = [UIImage imageNamed:@"社保认证身份证"];
    [self.view addSubview:idImg];
    
    
    [idImg mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(nameImg.mas_bottom);
        make.left.right.height.equalTo(nameImg);
    }];
    
    UITextField*tf_id = [[UITextField alloc]init];
    tf_id.textColor = [UIColor colorWithHex:0x4d4d4d];
    tf_id.font = [UIFont systemFontOfSize:15 * WIDTHRADIU];
    tf_id.placeholder = @"请输入身份证信息";
    tf_id.inputView = self.keyboardView.inputView;
    //tf_id.delegate = self;
    self.idText = tf_id;
    [self.view addSubview:tf_id];
    
    [tf_id mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(idImg);
        make.right.equalTo(idImg.mas_right).offset(-40 * WIDTHRADIU);
        make.left.equalTo(idImg.mas_left).offset(85 * WIDTHRADIU);
        make.height.equalTo(idImg.mas_height).multipliedBy(0.85);
    }];
    
    
    UIButton* btn_scan  = [UIButton buttonWithType:UIButtonTypeCustom];
    [btn_scan setImage:[UIImage imageNamed:@"my_Socialsecuritytermination_deathcertificate_IDscanning_normal"] forState:UIControlStateNormal];
    [btn_scan addTarget:self action:@selector(scanClick:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:btn_scan];
    
    [btn_scan mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(tf_id);
        make.left.equalTo(tf_id.mas_right).offset(7 * WIDTHRADIU);
    }];
    
    [self.view layoutIfNeeded];
    
    BOOL show = [UserDefault boolForKey:@"authPopShow"];
    if (!show) {
        
        
        //提示图标
       __block UIImageView *popView = [UIImageView new];
        
        popView.frame = CGRectMake(ScreenWidth - 200 * WIDTHRADIU, CGRectGetMaxY(idImg.frame) - 7* WIDTHRADIU, 180 * WIDTHRADIU, 36.5 * WIDTHRADIU);
        popView.alpha = 0;
         
        UIImage* popImage = [UIImage imageNamed:@"auth_popbg"];
        
        popView.image = popImage;
        
        [self.view addSubview:popView];
        
        UILabel *lb_message = [UILabel new];
        lb_message.text = @"拍摄身份证，自动录入信息";
        lb_message.font = [UIFont systemFontOfSize:13 * WIDTHRADIU];
        lb_message.textColor = [UIColor whiteColor];
        lb_message.numberOfLines = 0;
        lb_message.textAlignment = NSTextAlignmentCenter;
        [popView addSubview:lb_message];
        [lb_message mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerX.equalTo(popView);
            make.left.offset(2);
            make.top.offset(13 * WIDTHRADIU);
            make.right.offset(-2);
        }];
        
        [UIView animateWithDuration:0.5 animations:^{
            popView.alpha = 1.0;
        } completion:^(BOOL finished) {
            
            [UserDefault setBool:YES forKey:@"authPopShow"];
            
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(10 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                if (popView) {
                    
                    [UIView animateWithDuration:0.5 animations:^{
                        popView.alpha = 0;
                    } completion:^(BOOL finished) {
                        [popView removeFromSuperview];
                    }];
                    
                }
                
            });
        }];
    }
    
    
    
    
    
    
    //身份核验按钮
    UIButton* confirmBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [confirmBtn setTitle:@"身份核验" forState:UIControlStateNormal];
    [confirmBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    confirmBtn.titleLabel.font = [UIFont systemFontOfSize:17];
    confirmBtn.backgroundColor = [UIColor colorWithHex:0x086ed7];
    confirmBtn.layer.cornerRadius = 5 * WIDTHRADIU;
    [confirmBtn addTarget:self action:@selector(confirmBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:confirmBtn];
    
    [confirmBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.offset(10 * WIDTHRADIU);
        make.right.offset(- 10 * WIDTHRADIU);
        make.top.equalTo(idImg.mas_bottom).offset(50 * WIDTHRADIU);
        make.height.offset(45 * WIDTHRADIU);
    }];
    
    
    //人脸核验时请注意
    UIImageView* bottomBg = [UIImageView new];
    bottomBg.image = [UIImage imageNamed:@"auth_attention"];
    [self.view addSubview:bottomBg];
    
    [bottomBg mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.view);
        make.bottom.offset(- 25 * WIDTHRADIU);
        make.width.offset(335 * WIDTHRADIU);
        make.height.offset(98 * WIDTHRADIU);
    }];
    
    
    
}

#pragma mark - 实名认证接口
- (NSDictionary *)updateAccountAuthStateRequestPara:(NSString *)base64Str {
    
    NSString*nameText = [self.nameText.text stringByReplacingOccurrencesOfString:@" " withString:@""];
    NSString*idText = [self.idText.text stringByReplacingOccurrencesOfString:@" " withString:@""];
    NSString*name =  [EnercryTool AES256Encrypt:nameText key:DESKEY];
    NSString*idNo =  [EnercryTool AES256Encrypt:idText key:DESKEY];
    
    //random
    NSInteger randomInt = arc4random() % 10001;
    NSString* timeStamp = [NSString getNowTimeTimestamp3];
    
    NSString* nonce = [NSString stringWithFormat:@"%@%@",timeStamp,@(randomInt)];
    
    NSDictionary* params = @{
        @"loginId": @([getPeopleID PeopleID]),
        @"name":name,
        @"idcard":idNo,
        @"tel":[EnercryTool AES256Encrypt:[getPeopleID PeopleIphoneNmber] key:DESKEY],
        @"timestamp":timeStamp,
        @"nonce":nonce,
        @"image":base64Str
    };
    return params;
}

- (void)updateAccountAuthStateRequest:(NSString *)base64Str {
    NSString *urlString = [NSString stringWithFormat:@"%@%@",[NetworkConfig ipESSCConfig],KKUpdateAccountStateRequest];
    NSLog(@"实名认证接口url:%@",urlString);
   // NSLog(@"params:%@",[self updateAccountAuthStateRequestPara:base64Str]);
    
    
    NSMutableDictionary* newParams = [NSMutableDictionary dictionaryWithDictionary:[self updateAccountAuthStateRequestPara:base64Str]];
    
    
    
    if (newParams.allKeys.count > 0) {
        
    
        
        
        NSArray *allKeyArray = [newParams allKeys];
        //序列化器对数组进行排序的block 返回值为排序后的数组
        NSArray *afterSortKeyArray = [allKeyArray sortedArrayUsingComparator:^NSComparisonResult(id  _Nonnull obj1, id  _Nonnull obj2) {
            NSComparisonResult resuest = [obj1 compare:obj2];
            return resuest;
        }];
        NSLog(@"afterSortKeyArray:%@",afterSortKeyArray);
        
        NSString* versionsign = nil;
        
        for (NSString *sortsing in afterSortKeyArray) {
            
            if (![Tools dx_isNullOrNilWithObject:newParams[sortsing]]) {
                if (versionsign == nil) {
                    versionsign = [NSString stringWithFormat:@"%@=%@",sortsing,newParams[sortsing]];
                }else{
                    versionsign = [NSString stringWithFormat:@"%@&%@=%@",versionsign,sortsing,newParams[sortsing]];
                }
            }
            
        }
        
        
        
        if (versionsign) {
            versionsign = [NSString stringWithFormat:@"%@&adcb57e5a7ca28ff1b65ea8dfcab3de2",versionsign];
            
            versionsign = [MyMD5 md5:versionsign];
        }
        
        
        [newParams setObject:versionsign forKey:@"sign"];
    
    }
    
    [KKLoadingAnimationView show];
    [NetworkRequest Post12:urlString Params:newParams Success:^(id _Nonnull objc) {
        [KKLoadingAnimationView dismiss];
        NSLog(@"objc:%@",objc);
        if ([objc isKindOfClass:[NSDictionary class]]) {
            NSString* state = [NSString stringWithFormat:@"%@",objc[@"state"]];
            NSString* describe = [NSString stringWithFormat:@"%@",objc[@"describe"]];
            if ([state isEqualToString:@"200"]) {
                
                
                
                
                [getPeopleID saveAccountAuthWithState:YES];
                
                if (self.block) {
                    self.block(YES);
                }
                
                [[NSNotificationCenter defaultCenter] postNotificationName:KKSBLoginGetMaxAuthNumberNotificationName object:nil userInfo:nil];
                [[NSNotificationCenter defaultCenter] postNotificationName:KKSBAccountAuthNotificationName object:nil userInfo:nil];
                
                
                switch (self.type) {
                    case KKUserAuthFromVCTypeSBAuth:
                    {
                        [SVProgressHUD showSuccessWithStatus:@"实名成功,继续社保认证"];
                        [self backAuthVC];
                    }
                        break;
                    case KKUserAuthFromVCTypeBuTie:
                    {
                        [SVProgressHUD showSuccessWithStatus:@"实名成功,继续补贴认证"];
                        [self backAuthVC];
                    }
                        
                        break;
                    case KKUserAuthFromVCTypeYouFu:
                    {
                        [SVProgressHUD showSuccessWithStatus:@"实名成功,继续优抚认证"];
                        [self backAuthVC];
                    }
                        
                        break;
                    case KKUserAuthFromVCTypeDDSBCard:
                    {
                        [SVProgressHUD showSuccessWithStatus:@"实名成功,继续领取电子社保卡"];
                        [self backAuthVC];
                    }
                        
                        break;
                    case KKUserAuthFromVCTypeChangLiang:
                    {
                        [SVProgressHUD showSuccessWithStatus:@"实名成功,继续开通存钱罐"];
                        [self.navigationController popViewControllerAnimated:YES];
                    }
                        break;
                    case KKUserAuthFromVCTypeAccount:
                    {
                        if ([objc[@"result"] isKindOfClass:[NSDictionary class]]) {
                            NSString* idcard = [NSString stringWithFormat:@"%@",objc[@"result"][@"idcard"]];
                            NSString* name = [NSString stringWithFormat:@"%@",objc[@"result"][@"name"]];
                            
                            KKUserAuthSuccessViewController* vc = [KKUserAuthSuccessViewController new];
                            vc.nameTT = name;
                            vc.numTT = idcard;
                            vc.type = self.type;
                            vc.title = @"实名认证";
                            [self.navigationController pushViewController:vc animated:YES];
                        }
                    }
                        
                        break;
                    case KKUserAuthFromVCTypeUpdate:
                        [Tools showMessage:describe];
                        [self.navigationController popToRootViewControllerAnimated:YES];
                        break;
                        
                    default:
                        break;
                }
                
               
                
                
                
                
                
               
            }else {
                [self alertShowMessage:describe];
            }
            
            
        }else{
            [self alertShowMessage:@"服务器异常"];
        }
        
        
    } Failure:^(NSError* error) {
        [KKLoadingAnimationView dismiss];
        NSLog(@"error:%@",error);
        [self alertShowMessage:@"网络异常"];
        
    }];
}

#pragma mark - 判断用户是否重复实名
- (NSDictionary *)judgeAccountAuthRequestParams {
    NSString*tel =  [getPeopleID PeopleIphoneNmber];
    
    tel = [EnercryTool AES256Encrypt:tel key:DESKEY];
    
    NSString*nameText = [self.nameText.text stringByReplacingOccurrencesOfString:@" " withString:@""];
    NSString*idText = [self.idText.text stringByReplacingOccurrencesOfString:@" " withString:@""];
    NSString*name =  [EnercryTool AES256Encrypt:nameText key:DESKEY];
    NSString*idNo =  [EnercryTool AES256Encrypt:idText key:DESKEY];
    NSDictionary *dic = @{
           @"tel":tel,
           @"name":name,
           @"idCard":idNo
       };
    
    return dic;
}

- (void)judgeAccountAuthStateRequest {
    
    NSString *urlString = [NSString stringWithFormat:@"%@%@",[NetworkConfig ipESSCConfig],KKCheckRepeatAuthRequest];
    NSLog(@"判断账户是否重复实名url:%@",urlString);
    NSLog(@"params:%@",[self judgeAccountAuthRequestParams]);
    [KKLoadingAnimationView show];
    [NetworkRequest SBAuthPost:urlString Params:[self judgeAccountAuthRequestParams] Success:^(id _Nonnull objc) {
        [KKLoadingAnimationView dismiss];
        NSLog(@"objc:%@",objc);
        if ([objc isKindOfClass:[NSDictionary class]]) {
            NSString* code = [NSString stringWithFormat:@"%@",objc[@"state"]];
            NSString* describe = [NSString stringWithFormat:@"%@",objc[@"describe"]];
            if ([code isEqualToString:@"200"]) {
                
                [Tools showMessage:describe];
                
            }else if ([code isEqualToString:@"204"]) {
                
                [self skipToFaceVC];
            }else {
                [self alertShowMessage:describe];
            }
        }else{
            [self alertShowMessage:@"服务器异常"];
        }
        
        
    } Failure:^(NSError* error) {
        [KKLoadingAnimationView dismiss];
        NSLog(@"error:%@",error);
        [self alertShowMessage:@"网络异常"];
        
    }];
}



#pragma mark - passImagesDelegate
- (void)passImages:(NSArray *)imagesArray {
    
//    NSArray*newImageArray = [imagesArray sortedArrayUsingComparator:^NSComparisonResult(id  _Nonnull obj1, id  _Nonnull obj2) {
//         FaceImageModel *model1 = (FaceImageModel *)obj1;
//        FaceImageModel *model2 = (FaceImageModel *)obj2;
//         // 因为不满足sortedArrayUsingComparator方法的默认排序顺序，则需要交换
//         if (model1.score < model2.score) return NSOrderedDescending;
//         return NSOrderedAscending;
//     }];

     NSMutableArray *originImage = [[NSMutableArray alloc]init];
     for (int i = 0; i < imagesArray.count; i++) {



         FaceImageModel*imageModel = imagesArray[i];
         [originImage addObject:imageModel.image];
        

     }
    
    
    
    if (originImage.count > 0) {
        NSString*base64Str = [self changImageBase64:originImage[0]];

        if (base64Str) {
            [self updateAccountAuthStateRequest:base64Str];
        }
    }
//    UIImage *image1=  [SecondSocialViewController image:originImage[0] rotation:UIImageOrientationLeft];
    
//    TestViewController *vc = [Storyboard instantiateViewControllerWithIdentifier:@"TestViewController"];
//    vc.title = @"查看图片";
//    //vc.imageArray = imagesArray;
//    vc.image = image1;
//    [self.navigationController pushViewController:vc animated:YES];
    
}

- (void)passFail {
    
}


#pragma mark - SCNavigationControllerDelegate
- (void)sendIDCValue:(NSString *)name SEX:(NSString *)sex FOLK:(NSString *)folk BIRTHDAY:(NSString *)birthday ADDRESS:(NSString *) address NUM:(NSString *)num
{
    self.nameText.text =name;

    if (![IDCardNumber_Validate isValidateIDCardString:num]) {
        [SVProgressHUD showInfoWithStatus:@"身份证识别错误,请重新拍摄"];
        return;
    }
    NSString *st1 =[num substringWithRange:NSMakeRange(0, 6)];
    NSString *st2 =[num substringWithRange:NSMakeRange(6, 4)];
    NSString *st3 =[num substringWithRange:NSMakeRange(10, 4)];
    NSString *st4 =[num substringFromIndex:14];
    self.idText.text =  [NSString stringWithFormat:@"%@ %@ %@ %@",st1,st2,st3,st4];
    //self.idText.enabled = NO;//(扫描完身份证之后身份证号码不让修改,19年5月16号改...)
}

- (void)sendAllValue:(NSString *)text
{
    NSLog(@"all  = %@",text);
    
}
- (void)sendIDCBackValue:(NSString *)issue PERIOD:(NSString *) period
{
    NSLog(@"idcback  = %@\n%@\n",issue,period);
}
- (void)sendCardFaceImage:(UIImage *)image
{
//    if (image != NULL) {
//
//        NSData *small = UIImagePNGRepresentation(image);
//
//        self.ocrBase64_ = [small base64EncodedStringWithOptions:0];
//    }

}
- (void)sendFieldImage:(TFIELDID) filed  image:(UIImage *)fieldimage
{
    
    NSLog(@"sendFieldImage = %d %@\n",filed,fieldimage);

}
- (void)sendTakeImage:(TCARD_TYPE) iCardType image:(UIImage *)cardImage
{
    NSLog(@"sendTakeImage = %d %@\n",iCardType,cardImage);


//  NSData *small =UIImageJPEGRepresentation([self imageByScalingAndCroppingForSize:CGSizeMake(667, 375) and:cardImage], 1.0);
//  self.ocrBase64 = [small base64EncodedStringWithOptions:0];

}
- (void)sendIDCARDBackAction
{
    
}

#pragma mark - KKIDKeyboardViewDelegate
/**代理方法*/
-(void)clickKeyboardButton:(UIButton*)button{
    
    NSMutableString *str=[NSMutableString stringWithString:self.idText.text];

            switch (button.tag) {
                //1，删除按钮
                case 103:
                    AudioServicesPlaySystemSound(1105);//按键时播放系统声音
                    if ([str isEqualToString:@""])  return;//若密码框为空直接return，
                    
                    NSRange range={str.length-1,1};
                    [str deleteCharactersInRange:range];
                    self.idText.text=str;
                    break;
                    
                //5，其他按钮
                default:
                    AudioServicesPlaySystemSound(1104);
                    if (self.idText.text.length < 21) {
                        if (self.idText.text.length   == 6 || self.idText.text.length   == 11 || self.idText.text.length   == 16 ) {
                            self.idText.text = [self.idText.text stringByAppendingString:[NSString stringWithFormat:@" %@",button.currentTitle]];

                                }else{
                        self.idText.text=[self.idText.text stringByAppendingString:button.currentTitle];
                    }
                        
                    }
                    
                    break;
            }
    
}

#pragma mark - 提示
- (void)alertShowMessage:(NSString *)msg
{
    if (@available(iOS 9.0,*)) {
        
        UIAlertController * alertV = [UIAlertController alertControllerWithTitle:@"提示" message:msg preferredStyle:UIAlertControllerStyleAlert];
        
        UIAlertAction *confirm = [UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            
        }];
        
        [alertV addAction:confirm];
        
        [self presentViewController:alertV animated:YES completion:nil];
        
    }else{
        UIAlertView *alertV = [[UIAlertView alloc]initWithTitle:@"提示" message:msg delegate:self cancelButtonTitle:@"确定" otherButtonTitles: nil];
        [alertV show];
    }
}

#pragma mark - event response
- (void)backClick {
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)scanClick:(UIButton *)sender {
    SCCaptureCameraController *con = [[SCCaptureCameraController alloc] init];
    con.scNaigationDelegate = self;
    con.iCardType = TIDCARD2;
    con.isDisPlayTxt = NO;
    //con.TimeKey = TimeKeyS;
    con.ScanMode = TIDC_SCAN_MODE;
    [self presentViewController:con animated:YES completion:NULL];
}

- (void)confirmBtnClick:(UIButton *)sender {
    
    [self.view endEditing:YES];
    
    NSString*nameText = [self.nameText.text stringByReplacingOccurrencesOfString:@" " withString:@""];
    NSString*idText = [self.idText.text stringByReplacingOccurrencesOfString:@" " withString:@""];
    if (nameText.length == 0) {
        [Tools showMessage:@"请输入姓名!"];
        return;
    }
    
    if (![IDCardNumber_Validate isValidateIDCardString:idText]) {
        [Tools showMessage:@"身份证号格式不正确"];
        return;
    }
    
    if (self.type == KKUserAuthFromVCTypeUpdate) {
        [self judgeAccountAuthStateRequest];
    }else{
        [self skipToFaceVC];
    }
   
    
    
}


#pragma mark - 弹起活体检测
- (void)skipToFaceVC {
    LivenessViewController* dvc = [[LivenessViewController alloc] init];
    dvc.delegate = self;
    NSArray *array_ =nil;
                            
    array_ =[[NSArray alloc]initWithObjects:@1, nil];
  

    [dvc livenesswithList:array_ order:YES numberOfLiveness:0];
    [self presentViewController:dvc animated:YES completion:nil];
}

#pragma mark - 回到认证页面
- (void)backAuthVC {
    for (UIViewController* vc in self.navigationController.viewControllers) {
        if ([vc isKindOfClass:[KKUserIdentifyViewController class]]) {
            [self.navigationController popToViewController:vc animated:YES];
            break;
        }
        
        if ([vc isKindOfClass:[DistrictAuthenticationPersonalInfoController class]]) {
            [self.navigationController popToViewController:vc animated:YES];
            break;
        }
        
        if ([vc isKindOfClass:[DDSBCardViewController class]]) {
            [self.navigationController popToViewController:vc animated:YES];
            break;
        }
        
        
    }
}


#pragma mark - 通知绑定方法
- (void)jiePing {
    [self alertShowMessage:@"[安全提醒]内含身份信息，只适合当面使用。不要截图或分享给他人以保障信息安全。"];
}


#pragma mark - 图片处理
-(NSString*)imageChangeType:(UIImage*)selfImage{
    UIImage *  flippedImage= selfImage;
    //这里做了修改2017年6月27日
    //先获取图片的镜面图像
    flippedImage  = [UIImage imageWithCGImage:flippedImage.CGImage
                                        scale:1.0 orientation: UIImageOrientationUpMirrored];
    //2017年6月27日
    //2017年7月17日 (483,664)  -->  (360,270)
    //压缩到某一尺寸
    flippedImage=  [self imageByScalingAndCroppingForSize:CGSizeMake(360, 270) and:flippedImage];
    //压缩
    NSData  *dateImage1 =UIImageJPEGRepresentation( flippedImage,0.86);
    //编码
    NSString *str3=[EnercryTool encryptBase64:dateImage1];
    return str3;
    
}

#pragma mark - 图片压缩到某一尺寸
- (UIImage*)imageByScalingAndCroppingForSize:(CGSize)targetSize and:(UIImage*)imageKs
{
    UIImage *sourceImage = imageKs;
    UIImage *newImage = nil;
    CGSize imageSize = sourceImage.size;
    CGFloat width = imageSize.width;
    CGFloat height = imageSize.height;
    CGFloat targetWidth = targetSize.width;
    CGFloat targetHeight = targetSize.height;
    CGFloat scaleFactor = 0.0;
    CGFloat scaledWidth = targetWidth;
    CGFloat scaledHeight = targetHeight;
    CGPoint thumbnailPoint = CGPointMake(0.0,0.0);
    
    if (CGSizeEqualToSize(imageSize, targetSize) == NO)
    {
        CGFloat widthFactor = targetWidth / width;
        CGFloat heightFactor = targetHeight / height;
        
        if (widthFactor > heightFactor)
            scaleFactor = widthFactor; // scale to fit height
        else
            scaleFactor = heightFactor; // scale to fit width
        scaledWidth= width * scaleFactor;
        scaledHeight = height * scaleFactor;
        
        // center the image
        if (widthFactor > heightFactor)
        {
            thumbnailPoint.y = (targetHeight - scaledHeight) * 0.5;
        }
        else if (widthFactor < heightFactor)
        {
            thumbnailPoint.x = (targetWidth - scaledWidth) * 0.5;
        }
    }
    
    //UIGraphicsBeginImageContext(targetSize); // this will crop
    UIGraphicsImageRenderer*re=[[UIGraphicsImageRenderer alloc] initWithSize:targetSize];
    CGRect thumbnailRect = CGRectZero;
    thumbnailRect.origin = thumbnailPoint;
    thumbnailRect.size.width= scaledWidth;
    thumbnailRect.size.height = scaledHeight;
    
    [sourceImage drawInRect:thumbnailRect];
    
    newImage = UIGraphicsGetImageFromCurrentImageContext();
    if(newImage == nil)
        NSLog(@"could not scale image");
    
    //pop the context to get back to the default
    UIGraphicsEndImageContext();
    return newImage;
}


#pragma mark - 获取自定义行间隔富文本
- (NSAttributedString *)getAttributedStringWithString:(NSString *)text lineSpace:(CGFloat)lineSpace kern:(CGFloat)kern {
    NSMutableParagraphStyle *paragraphStyle = [NSMutableParagraphStyle new];
    //调行行间距
    paragraphStyle.lineSpacing = lineSpace;
    paragraphStyle.alignment = NSTextAlignmentCenter;
    
    NSDictionary*attriDict =@{NSParagraphStyleAttributeName:paragraphStyle,NSKernAttributeName:@(kern),NSFontAttributeName:[UIFont systemFontOfSize:16 * WIDTHRADIU],NSForegroundColorAttributeName:[UIColor whiteColor]};
    NSMutableAttributedString*attributedString = [[NSMutableAttributedString alloc]initWithString:text attributes:attriDict];
    return attributedString;
}

#pragma mark - getters
-(KKIDKeyboardView*)keyboardView{
    if (!_keyboardView) {
        _keyboardView=[KKIDKeyboardView loadKeyboardFromNib];
    
        _keyboardView.frame=CGRectMake(0, 0, ScreenWidth, 216);
        
        //1,第一种方式使用代理
        _keyboardView.delegate=self;
        
        //2,第二种方式使用block
        /**
        
        __weak typeof(self) weakSelf=self;
        _keyboardView.clickBlock = ^(UIButton *button) {
            [weakSelf clickKeyboardButton:button];
        };
         
         */
    }
    return _keyboardView;
}
/*
#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
