//
//  DDSBCardViewController.m
//  Open
//
//  Created by 雷俊博 on 2020/10/16.
//  Copyright © 2020 黄江涛 . All rights reserved.
//

#import "DDSBCardViewController.h"
#import "DDSBCardListVC.h"
#import "AppDelegate.h"

#import "KKIDKeyboardView.h"
#import "KKUserAuthViewController.h"

#import "UITextField+CursorPosition.h"
#import "KKBanCopyPasteTextField.h"

@interface DDSBCardViewController ()<UITextFieldDelegate,UIScrollViewDelegate,KKIDKeyboardViewDelegate>

@property (nonatomic, strong)UIScrollView* scrollView;

@property (nonatomic, strong)UIView*backImgView;

@property (nonatomic, strong)UIImageView* topCircleImg;

@property (nonatomic, strong)UIImageView* nameImg;

@property (nonatomic, strong)UITextField*nameText;

@property (nonatomic, strong)KKBanCopyPasteTextField*IDText;

@property (nonatomic, strong)UIButton* PhotoBtn;

@property(nonatomic,strong)KKIDKeyboardView *keyboardView;

@end

@implementation DDSBCardViewController

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    [GTCountSDK trackCountEvent:@"home_ESSCard_commitInfoPage" withArgs:nil];
    
    [self.navigationController setNavigationBarHidden:NO animated:animated];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor colorWithHex:0xf4f4f4];
    
    [self.view addSubview:self.scrollView];
    
     [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(backToCardListVC) name:KKSBESSCCARDBindCardNotificationName object:nil];
    
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(jiePing) name:UIApplicationUserDidTakeScreenshotNotification  object:nil];
}

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

#pragma mark - 通知绑定事件
- (void)backToCardListVC
{
    BOOL isExist = NO;
    for (UIViewController*vc in self.navigationController.viewControllers) {
        if ([vc isKindOfClass:[DDSBCardListVC class]]) {
            isExist = YES;
            DDSBCardListVC* dVC = (DDSBCardListVC *)vc;
            dVC.noStart = YES;
            [self .navigationController popToViewController:dVC animated:YES];
            break;
        }
    }
    
    
    if (isExist == NO) {
        
        DDSBCardListVC* listVC = [DDSBCardListVC new];
        listVC.title = @"电子社保卡";
        listVC.hidesBottomBarWhenPushed = YES;
        listVC.noStart = YES;
        
        NSMutableArray* vcArray = [NSMutableArray arrayWithArray:self.navigationController.viewControllers];
        [vcArray insertObject:listVC atIndex:1];
        self.navigationController.viewControllers = vcArray;
        
        [self.navigationController popViewControllerAnimated:YES];
    }
    
}

#pragma mark - 判断是否是真实姓名请求
- (NSDictionary *)judgeRealNameRequestPara
{
    NSString*nameText = [self.nameText.text stringByReplacingOccurrencesOfString:@" " withString:@""];
    NSString*idText = [self.IDText.text stringByReplacingOccurrencesOfString:@" " withString:@""];
    NSString*name =  [EnercryTool A:nameText];
    NSString*idNo =  [EnercryTool A:idText];
    NSDictionary *dic = @{
           @"name":name,
           @"idcard":idNo
       };
    return dic;
}
- (void)judgeRealNameRequest
{
    NSString *urlString = [NSString stringWithFormat:@"%@%@",[NetworkConfig ipKKSBConfig],KKESSCRealNameRequest];
    NSLog(@"绑定电子社保卡列表url:%@",urlString);
    NSLog(@"params:%@",[self judgeRealNameRequestPara]);
    [KKLoadingAnimationView show];
     [NetworkRequest baseGet:urlString Params:[self judgeRealNameRequestPara] Success:^(id _Nonnull responseObject) {
         [KKLoadingAnimationView dismiss];
         
         NSLog(@"responseObject:%@",responseObject);
         NSString*state = [NSString stringWithFormat:@"%@",responseObject[@"state"]];
         NSString*describe = [NSString stringWithFormat:@"%@",responseObject[@"describe"]];
         if ([state isEqualToString:@"200"]) {
             
            NSString*nameText = [self.nameText.text stringByReplacingOccurrencesOfString:@" " withString:@""];
            NSString*idText = [self.IDText.text stringByReplacingOccurrencesOfString:@" " withString:@""];
            NSString*name =  [EnercryTool A:nameText];
            NSString*idNo =  [EnercryTool A:idText];
              
              name = [name stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
              idNo = [idNo stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
              
              NSDictionary *dic = @{
                                    @"name":name,
                                    @"elecCard":idNo
                                    };
             
//              [[SDKManage ShareSDKManage] initWithHost:TESTHOST accessKey:@"" channelNo:@""];
//              [[SDKManage ShareSDKManage] requestSignStringAndOpenSDKFromVC:self param:dic path:@"/base/info"];
//              
//              [UserDefault setObject:name forKey:@"kkESSCName"];
//              [UserDefault setObject:idNo forKey:@"kkESSCIDNo"];
//              [UserDefault synchronize];
             
         }else{
             [SVProgressHUD showErrorWithStatus:describe];
         }
         
         
     } Failure:^(NSError* error) {
         [KKLoadingAnimationView dismiss];
         NSLog(@"error:%@",error);
         [SVProgressHUD showErrorWithStatus:@"网络异常"];
     }];
}

#pragma mark - 判断账户是否已实名
- (NSDictionary *)judgeAccountAuthRequestParams {
    NSString*tel =  [getPeopleID PeopleIphoneNmber];
    
    tel = [EnercryTool AES256Encrypt:tel key:DESKEY];
    NSDictionary *dic = @{
           @"tel":tel
       };
    
    return dic;
}

- (void)judgeAccountAuthStateRequest {
    NSString *urlString = [NSString stringWithFormat:@"%@%@",[NetworkConfig ipKKSBConfig],KKCheckAccountStateRequest];
    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"]) {
                
               
                
            }else if ([code isEqualToString:@"204"]) {
                
                NSString*nameText = [self.nameText.text stringByReplacingOccurrencesOfString:@" " withString:@""];
                NSString*idText = [self.IDText.text stringByReplacingOccurrencesOfString:@" " withString:@""];
                
                [SVProgressHUD showErrorWithStatus:@"该账户尚未实名,请先实名后再认证电子社保卡"];
                KKUserAuthViewController* vc = [KKUserAuthViewController new];
                vc.title = @"实名认证";
                vc.nameTT = nameText;
                vc.numTT = idText;
                vc.hidesBottomBarWhenPushed = YES;
                [self.navigationController pushViewController:vc animated:YES];
            }else {
                [self alertShowMessage:describe];
            }
        }else{
            [self alertShowMessage:@"服务器异常"];
        }
        
        
    } Failure:^(NSError* error) {
        [KKLoadingAnimationView dismiss];
        NSLog(@"error:%@",error);
        [self alertShowMessage:@"网络异常"];
        
    }];
}




#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;
    }else{
        self.nameText.userInteractionEnabled = YES;
    }
    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 refreshBtnState];
}




#pragma mark - UITextFieldDelegate
- (BOOL)textFieldShouldReturn:(UITextField *)textField{
    [textField resignFirstResponder];
    return YES;
}
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    
    NSCharacterSet *_set = [NSCharacterSet characterSetWithCharactersInString:@"0123456789xX"];;
    
    [self refreshBtnState];
    
    if (textField == self.IDText) {
        if ([string isEqualToString:@""]) { // 删除字符
            return YES;
        } else {
            
            if (textField.text.length   == 6 || textField.text.length   == 11 || textField.text.length   == 16 ) {
                  textField.text = [NSString stringWithFormat:@"%@ ", textField.text];

                    }
            }

            
             if (textField.text.length >= 21)
             {//大于18位无法再继续输入
                               return NO;
             }
                           
            NSRange range = [string rangeOfCharacterFromSet:_set];
            //判断输入的内容是否是规定的内容范围内 如果不是不做更改 如果是才输入
           if (range.length == 0) {
               return NO;
           }else{
               return YES;
           }
        return YES;
    }
    return YES;
}

- (BOOL)textFieldShouldEndEditing:(UITextField *)textField
{
    
    [self refreshBtnState];
    return YES;
}

#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，
                    
//                    UITextRange *selRange = self.IDText.selectedTextRange;
//                    UITextPosition *selStartPos = selRange.start;
//                    NSInteger idx = [self.IDText offsetFromPosition:self.IDText.beginningOfDocument toPosition:selStartPos];
//                    if (idx == 0) {
//                        return;
//                    }
//
                    NSRange range={str.length - 1,1};
                    [str deleteCharactersInRange:range];
//                    self.IDText.cursorPosition = idx -1;
                    self.IDText.text=str;
                    [self refreshBtnState];
                }
                    

                    
                   
                    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];
                    }
                        
                       
                        [self refreshBtnState];
                    }
                    
                    break;
            }
    
}


#pragma mark - UIScrollViewDelegate
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    if (scrollView.contentOffset.y <= 0) {
        scrollView.contentOffset = CGPointMake(0, 0);
    }
}

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

#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 - 刷新按钮状态
- (void)refreshBtnState
{
    if (self.nameText.text.length == 0 || self.IDText.text.length <= 3) {
        self.PhotoBtn.backgroundColor =[UIColor colorWithRed:191/255.0 green:191/255.0 blue:191/255.0 alpha:1.0];
        self.PhotoBtn.userInteractionEnabled =NO;
    }else{
       self.PhotoBtn.backgroundColor =[UIColor colorWithRed:25/255.0 green:149/255.0 blue:109/255.0 alpha:1.0];
       self.PhotoBtn.userInteractionEnabled =YES;
    }
}

#pragma mark - event response
- (void)explainIdentifly:(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)photo:(UIButton *)sender{
    
    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;
    }
    
    [self judgeAccountAuthStateRequest];
    
   // [self judgeRealNameRequest];
    
    
    
    
    
    
}

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

- (UIScrollView *)scrollView
{
    if (!_scrollView) {
        _scrollView = [[UIScrollView alloc]initWithFrame:CGRectMake(0, cl_kNavigationBarHeight, ScreenWidth, ScreenHeight - cl_kNavigationBarHeight)];
        _scrollView.backgroundColor = [UIColor whiteColor];
        _scrollView.contentSize = CGSizeMake(ScreenWidth, ScreenHeight - cl_kNavigationBarHeight);
        _scrollView.showsHorizontalScrollIndicator = NO;
        _scrollView.showsVerticalScrollIndicator = NO;
        _scrollView.delegate = self;
        
        
        //背景图片
         UIView* topBackImg = [[UIView alloc]initWithFrame:CGRectMake(0, 0 *ScreenWidth, ScreenWidth, 345 * WIDTHRADIU)];
         topBackImg.backgroundColor = [UIColor colorWithHex:0xf7f7f7];
         topBackImg.userInteractionEnabled = YES;
         self.backImgView = topBackImg;
         [_scrollView addSubview:topBackImg];
         
        
        //姓名
       UIImageView*nameImg = [[UIImageView alloc]initWithFrame:CGRectMake(11 * WIDTHRADIU, 22 * WIDTHRADIU, ScreenWidth - 22 * WIDTHRADIU, (ScreenWidth - 22 * WIDTHRADIU) * 58/353.0)];
       nameImg.image = [UIImage imageNamed:@"社保认证姓名"];
       [topBackImg 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;
       [topBackImg 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:@"社保认证身份证"];
       [topBackImg addSubview:idImg];
       
       
       [idImg mas_makeConstraints:^(MASConstraintMaker *make) {
           make.top.equalTo(nameImg.mas_bottom);
           make.left.right.height.equalTo(nameImg);
       }];
       
       KKBanCopyPasteTextField*tf_id = [[KKBanCopyPasteTextField alloc]init];
       tf_id.textColor = [UIColor colorWithHex:0x4d4d4d];
       tf_id.font = [UIFont systemFontOfSize:15 * WIDTHRADIU];
       tf_id.placeholder = @"请输入身份证信息";
       tf_id.delegate = self;
       tf_id.inputView=self.keyboardView.inputView;
       self.IDText = tf_id;
       [topBackImg addSubview:tf_id];
       
       [tf_id mas_makeConstraints:^(MASConstraintMaker *make) {
           make.centerY.equalTo(idImg);
           make.right.equalTo(idImg.mas_right).offset(-20 * WIDTHRADIU);
           make.left.equalTo(idImg.mas_left).offset(85 * WIDTHRADIU);
           make.height.equalTo(idImg.mas_height).multipliedBy(0.85);
       }];
        
       
        
        CGFloat cardWidth = (ScreenWidth - 56 * WIDTHRADIU - 50) * 0.52;
        CGFloat buttonWidth = (ScreenWidth - 56 * WIDTHRADIU - 50) * 0.45;
        //身份证图片
        UIImageView*IdCardView = [[UIImageView alloc]init];
        IdCardView.image = [UIImage imageNamed:@"身份证图"];
        [topBackImg addSubview:IdCardView];
        
        [IdCardView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.offset(28 * WIDTHRADIU + 25);
            make.top.equalTo(idImg.mas_bottom).offset(5 * WIDTHRADIU);
            make.width.offset(cardWidth);
            make.height.offset(90/141.0 * cardWidth);
        }];
    
        //例
        UILabel* lb_li = [[UILabel alloc]init];
        lb_li.text = @"例:";
        lb_li.textColor = [UIColor colorWithHex:0x7b7b7b];
        lb_li.font = [UIFont systemFontOfSize:19];
        [topBackImg addSubview:lb_li];
        
        [lb_li mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.offset(28 * WIDTHRADIU);
            make.centerY.equalTo(IdCardView);
            make.width.offset(25);
            make.height.offset(42);
        }];
    
    
        //button
        UIButton* btn = [UIButton buttonWithType:UIButtonTypeCustom];
        [btn setTitle:@"拍身份证识别" forState:UIControlStateNormal];
        [btn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        btn.titleLabel.font = [UIFont systemFontOfSize:15 * WIDTHRADIU];
        btn.backgroundColor = [UIColor colorWithHex:0x239DED];
        btn.layer.cornerRadius = 4;
        [btn addTarget:self action:@selector(explainIdentifly:) forControlEvents:UIControlEventTouchUpInside];
        [topBackImg addSubview:btn];
        
        [btn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(IdCardView.mas_right).offset(25);
            make.centerY.equalTo(IdCardView);
            make.width.offset(buttonWidth);
            make.height.offset(40 * WIDTHRADIU);
        }];
        
        
        //uibutton
         UIButton* nextBtn = [UIButton buttonWithType:UIButtonTypeCustom];
         [nextBtn setTitle:@"下一步" forState:UIControlStateNormal];
         [nextBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
         nextBtn.backgroundColor = [UIColor colorWithHex:0xc5c5c5];
         nextBtn.titleLabel.font = [UIFont systemFontOfSize:15 * WIDTHRADIU];
         nextBtn.layer.cornerRadius = 5 * WIDTHRADIU;
         nextBtn.userInteractionEnabled = NO;
         self.PhotoBtn = nextBtn;
         [self.PhotoBtn addTarget:self action:@selector(photo:) forControlEvents:UIControlEventTouchUpInside];
         
        [_scrollView addSubview:nextBtn];
         
         [nextBtn mas_makeConstraints:^(MASConstraintMaker *make) {
             make.top.equalTo(IdCardView.mas_bottom).offset(30);
             make.left.right.equalTo(nameImg);
             make.height .offset(45 * WIDTHRADIU);
         }];
        
    }
    return _scrollView;
}

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