//
//  SSTerminationViewController.m
//  Open
//
//  Created by 雷俊博 on 2019/7/26.
//  Copyright © 2019 黄江涛 . All rights reserved.
//

#import "SSTerminationViewController.h"
#import "Constants.h"

#import "XZDrawView.h"
#import "CTAPIBaseManager.h"

//OCR
#import "IOSOCRAPI.h"
#import "SCCaptureCameraController.h"
#import <esscsdk/esscsdk.h>
#import "rzUserModel.h"
#import "RZUserCollectionViewCell.h"
@interface SSTerminationViewController ()<UITextFieldDelegate,SCNavigationControllerDelegate,EESBCallbackDelegate,UIScrollViewDelegate,UICollectionViewDelegate,UICollectionViewDataSource>
{
    UICollectionView* _mainCollectionView;rzUserModel* userModel;}
//背景图
@property (nonatomic, strong)XZDrawView *backView;
//姓名
@property (nonatomic, strong)UIView *backView_Name;
@property (nonatomic, strong)UIView *view_Name;
@property (nonatomic, strong)UIView *subView_Name;
@property (nonatomic, strong)UIImageView *img_Name;
@property (nonatomic, strong)UITextField *tf_Name;
//身份证号
@property (nonatomic, strong)UIView *backView_IDNumber;
@property (nonatomic, strong)UIView *view_IDNumber;
@property (nonatomic, strong)UIView *subView_IDNumber;
@property (nonatomic, strong)UIImageView *img_IDNumber;
@property (nonatomic, strong)UITextField *tf_IDNumber;
@property (nonatomic, strong)UIButton *btn_scan;

@property (nonatomic, strong)UILabel *lb_Example;
@property (nonatomic, strong)UIImageView *img_Example;

@property (nonatomic, strong)UIImageView *video_Example;
@property (nonatomic, strong)UIView *leftLine;
@property (nonatomic, strong)UIView *rightLine;

@property (nonatomic, strong)UILabel *lb_title;


@property (nonatomic, strong)UIButton *btn_next;

@property (nonatomic, strong)UIView *frontView;
@property (nonatomic, strong)UIImageView *img_back;
@property (nonatomic,strong)UILabel *lb_name;
@property (nonatomic, strong)UILabel *lb_cardId;
@property (nonatomic, strong)NSMutableArray* dataArray;




@end

@implementation SSTerminationViewController
#pragma mark - life cycle
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self navConfig];
    [self.view addSubview:self.backView];
    [self.view addSubview:self.backView_Name];
    [self.view addSubview:self.backView_IDNumber];
    [self.view addSubview:self.video_Example];
    [self.view addSubview:self.img_Example];
    [self.view addSubview:self.lb_Example];
    [self.view addSubview:self.lb_title];
    [self.view addSubview:self.leftLine];
    [self.view addSubview:self.rightLine];
    [self.view addSubview:self.btn_next];
    
    self.view.backgroundColor = [UIColor whiteColor];
    //起点发生变化
    //self.edgesForExtendedLayout=UIRectEdgeBottom;
    
    [self showUI:YES];
    
    
    [self getOCR];
    
    
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(jiePing) name:UIApplicationUserDidTakeScreenshotNotification  object:nil];
    
    [self.backView_Name mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.offset(45 * WIDTHRADIU +cl_kNavigationBarHeight);
        make.left.offset(20 * WIDTHRADIU);
        make.right.offset(-20 * WIDTHRADIU);
        make.height.offset(45 * WIDTHRADIU);
    }];
    
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    // 设置item的行间距和列间距
    layout.minimumInteritemSpacing = 0;
    layout.minimumLineSpacing = 0;
    layout.scrollDirection = UICollectionViewScrollDirectionVertical;
    UICollectionView*collectionView = [[UICollectionView alloc]initWithFrame:CGRectZero collectionViewLayout:layout];
    collectionView.backgroundColor = [UIColor whiteColor];
    collectionView.showsVerticalScrollIndicator = NO;   //是否显示滚动条
    collectionView.scrollEnabled = YES;  //滚动使能
    collectionView.delegate = self;
    collectionView.dataSource = self;
    [collectionView registerNib:[UINib nibWithNibName:@"RZUserCollectionViewCell" bundle:nil] forCellWithReuseIdentifier:@"userCell"];
    [self.view addSubview:collectionView];
    _mainCollectionView = collectionView;
    
    
}
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    return 1;
}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return self.dataArray.count;
}
// The cell that is returned must be retrieved from a call to -dequeueReusableCellWithReuseIdentifier:forIndexPath:
- (__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    RZUserCollectionViewCell * cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"userCell" forIndexPath:indexPath];
    rzUserModel* model = self.dataArray[indexPath.item];
    cell.lb_firstName.text = [NSString stringWithFormat:@"%@",[model.name substringToIndex:1]];
    cell.lb_name.text = model.name;
    // cell.backgroundColor = [UIColor colorWithRed:(arc4random()%256)/256.0 green:(arc4random()%256)/256.0 blue:(arc4random()%256)/256.0 alpha:1.0];
    return cell;
}
/**
 cell的大小
 */
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    CGFloat width =  CGRectGetWidth(collectionView.bounds)  / self.dataArray.count ;
    CGFloat realWidth = CGRectGetWidth(collectionView.bounds)   - floor(width)*(self.dataArray.count - 1);
    // CGFloat itemW = K_ScreenWidth/array.count;
    if (indexPath.item == 0) {
        return CGSizeMake(realWidth, 61);
    }
    return CGSizeMake(floor(width), 61);
}
/**
 每个分区的内边距（上左下右）
 */
- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section{
    
    return UIEdgeInsetsMake(0, 0, 0, 0);
}
/**
 分区内cell之间的最小行间距
 */
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section{
    
    return 0;
}
/**
 分区内cell之间的最小列间距
 */
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section{
    return 0;
}
- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath {
    return nil;
}
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section {
    return CGSizeZero;
}
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    userModel = self.dataArray[indexPath.item];
    //todo 去电子社保卡
    [self getSSCardSign:userModel.name :userModel.idNumber];
}

-(void)alertSHOW:(NSString*)str{
    __weak __typeof(self)weakSelf = self;
    UIAlertController *alertCon =[UIAlertController alertControllerWithTitle:str message:nil preferredStyle:UIAlertControllerStyleAlert];
    [alertCon addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
    }]];
    [self presentViewController:alertCon animated:YES completion:nil];
}

- (void)backClick{
    [self.navigationController popViewControllerAnimated:YES];
}
- (void)navConfig{
    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 = @"电子社保卡";
     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);
     }];
     
     UIButton *orderBtn = [UIButton buttonWithType:UIButtonTypeCustom];
     orderBtn.frame = CGRectMake(ScreenWidth - 100, cl_kStatusBarHeight, 100, 44);
     [orderBtn setTitle:@"客服" forState:UIControlStateNormal];
     [orderBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
     orderBtn.titleLabel.font = [UIFont systemFontOfSize:15.0];
     [orderBtn addTarget:self action:@selector(gotoService) forControlEvents:UIControlEventTouchUpInside];
     [nav addSubview:orderBtn];
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
     [self.navigationController setNavigationBarHidden:NO animated:YES];
    //[self queryCardResult];
    @try {
        //此处写可能出现崩溃的代码
        //数组插入nil对象
        //[self showUser];
        [self creatTable];
    } @catch (NSException *exception) {
        //捕获到异常要执行的代码
        NSLog(@"exc == %@, 最后我弹了一个弹框说这样不合适",exception);
    } @finally {
        //不管能不能捕获到异常都会执行的方法
        NSLog(@"最后");
    }
}
- (NSString *)getDBPath{
     NSString *doc= [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
        return [doc stringByAppendingPathComponent:@"rzUserlist.sqlite"];

}
#pragma mark - 创建本地数据库
- (void)creatTable{
    //1.获得数据库文件的路径
    NSLog(@"表格路径:%@",[self getDBPath]);
     //2.获得数据库
    FMDatabase *db=[FMDatabase databaseWithPath:[self getDBPath]];
    if ([db open]) {
         //4.创表
        NSString* sql = @"CREATE TABLE IF NOT EXISTS t_rzUserSBCard (id integer PRIMARY KEY AUTOINCREMENT, name text NOT NULL, idNumber text NOT NULL, userid text NOT NULL,timeSp text);";
         BOOL result=[db executeUpdate:sql];
        if (result) {
            NSLog(@"创表成功");
            if (![db columnExists:@"timeSp" inTableWithName:@"t_rzUserSBCard"]){
                NSString *alertStr = [NSString stringWithFormat:@"ALTER TABLE %@ ADD %@ text",@"t_rzUserSBCard",@"timeSp"];
                BOOL worked = [db executeUpdate:alertStr];
                if(worked){
                    NSLog(@"插入成功");
                }else{
                    NSLog(@"插入失败");
                }
            }
            
        }else{
            NSLog(@"创表失败");
        }
        
        [db close];
    }
    [self queryData];
}

- (void)queryData{
    //1.获得数据库文件的路径
   NSLog(@"表格路径:%@",[self getDBPath]);
    NSMutableArray * array = [NSMutableArray array];
    //2.获得数据库
   FMDatabase *db=[FMDatabase databaseWithPath:[self getDBPath]];
    if ([db open]) {
        // 1.执行查询语句
        NSString * sql = [NSString stringWithFormat:@"SELECT * FROM t_rzUserSBCard where userid = '%ld'",[getPeopleID PeopleID]];
        FMResultSet *resultSet = [db executeQuery:sql];
        // 2.遍历结果
        while ([resultSet next]){
            int ID = [resultSet intForColumn:@"id"];
            NSString *name = [resultSet stringForColumn:@"name"];
            NSString *idNumber = [resultSet stringForColumn:@"idNumber"];
            NSString *userid = [resultSet stringForColumn:@"userid"];
            NSString *timeStamp = [resultSet stringForColumn:@"timeSp"];
            NSLog(@"ID:%d,name:%@,idNumber:%@,userid:%@",ID,name,idNumber,userid);
            rzUserModel*model = [[rzUserModel alloc]init];
            model.name = name;
            model.idNumber = idNumber;
            model.timeStamp = timeStamp;
            [array addObject:model];
        }
    }
    [db close];
    [self.dataArray removeAllObjects];
    [array.reverseObjectEnumerator.allObjects enumerateObjectsUsingBlock:^(rzUserModel* obj, NSUInteger idx, BOOL * _Nonnull stop) {
      [self.dataArray addObject:obj];
    }];
    
    if (self.dataArray.count == 0) {
        _mainCollectionView.hidden=true;
    }else{
        _mainCollectionView.hidden=false;
        [_mainCollectionView reloadData];
    }
}

- (NSMutableArray *)dataArray
{
    if (!_dataArray) {
        _dataArray = [NSMutableArray array];
    }
    return _dataArray;
}

- (void)viewWillLayoutSubviews{
    [super viewWillLayoutSubviews];
    
    
    [self.view_Name mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.bottom.right.offset(0);
    }];
    
    [self.subView_Name mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.top.bottom.offset(0);
        make.width.offset(65 * WIDTHRADIU);
    }];
    [self.img_Name mas_makeConstraints:^(MASConstraintMaker *make) {
        make.center.equalTo(self.subView_Name);
    }];
    
    [self.tf_Name mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.subView_Name.mas_right).offset(15 * WIDTHRADIU);
        make.top.bottom.offset(0);
        make.right.offset(-40 * WIDTHRADIU);
    }];
    
    
    
    [self.backView_IDNumber mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.backView_Name.mas_bottom).offset(20 * WIDTHRADIU);
        make.left.right.height.equalTo(self.backView_Name);
    }];
    
    [self.view_IDNumber mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.bottom.right.offset(0);
    }];
    
    [self.subView_IDNumber mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.top.bottom.offset(0);
        make.width.offset(65 * WIDTHRADIU);
    }];
    [self.img_IDNumber mas_makeConstraints:^(MASConstraintMaker *make) {
        make.center.equalTo(self.subView_IDNumber);
    }];
    
    [self.tf_IDNumber mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.subView_IDNumber.mas_right).offset(15 * WIDTHRADIU);
        make.top.bottom.offset(0);
        make.right.offset(-40 * WIDTHRADIU);
    }];
    
    [self.btn_scan mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(self.tf_IDNumber);
        make.left.equalTo(self.tf_IDNumber.mas_right).offset(7 * WIDTHRADIU);
    }];
    
    [self.img_Example mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.backView_IDNumber.mas_bottom).offset(20 * WIDTHRADIU);
        make.centerX.equalTo(self.backView_Name).offset(34 * WIDTHRADIU);
        make.height.offset(71 * WIDTHRADIU);
        make.width.offset(114*WIDTHRADIU);
    }];
    
    [self.video_Example mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.img_Example.mas_bottom).offset(20 * WIDTHRADIU);
        make.centerX.equalTo(self.backView_Name).offset(34 * WIDTHRADIU);
        make.height.offset(71 * WIDTHRADIU);
        make.width.offset(114*WIDTHRADIU);
    }];
    
//    [self.video_Example mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.top.equalTo(self.backView_IDNumber.mas_bottom).offset(20 * WIDTHRADIU);
//        make.centerX.equalTo(self.backView_Name).offset(34 * WIDTHRADIU);
//        make.height.offset(71 * WIDTHRADIU);
//        make.width.offset(114*WIDTHRADIU);
//    }];
//
//    [self.img_Example mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.top.equalTo(self.video_Example.mas_bottom).offset(20 * WIDTHRADIU);
//        make.centerX.equalTo(self.backView_Name).offset(34 * WIDTHRADIU);
//        make.height.offset(71 * WIDTHRADIU);
//        make.width.offset(114*WIDTHRADIU);
//    }];
    
    [self.lb_Example mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.backView_IDNumber.mas_bottom).offset(88*WIDTHRADIU);
        make.left.equalTo(self.video_Example.mas_left).offset(-35 * WIDTHRADIU);
    }];
    
    [self.lb_title mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.backView);
        make.top.equalTo(self.img_Example.mas_bottom).offset(20 * WIDTHRADIU);
        make.height.offset(14 * WIDTHRADIU);
    }];
    
    [self.leftLine mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(self.lb_title);
        make.right.equalTo(self.lb_title.mas_left).offset(-12 * WIDTHRADIU);
        make.left.offset(18 * WIDTHRADIU);
        make.height.offset(0.5);
    }];
    [self.rightLine mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(self.lb_title);
        make.left.equalTo(self.lb_title.mas_right).offset(12 * WIDTHRADIU);
        make.right.offset(-18 * WIDTHRADIU);
         make.height.offset(0.5);
    }];
    
    [_mainCollectionView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.backView.mas_bottom).offset(15 * WIDTHRADIU);
        make.left.right.offset(0);
        make.height.offset(62);
    }];
    if(self.dataArray.count == 0){//
        [self.btn_next mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(self.backView.mas_bottom).offset(15 * WIDTHRADIU);
            make.left.offset(18 * WIDTHRADIU);
            make.right.offset(- 18 * WIDTHRADIU);
            make.height.offset(45 * WIDTHRADIU);
        }];
    }else{
        [self.btn_next mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(_mainCollectionView.mas_bottom).offset(15 * WIDTHRADIU);
            make.left.offset(18 * WIDTHRADIU);
            make.right.offset(- 18 * WIDTHRADIU);
            make.height.offset(45 * WIDTHRADIU);
        }];
    }
    
//    [_mainCollectionView mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.top.equalTo(self.btn_next.mas_bottom).offset(10 * WIDTHRADIU);
//        make.left.right.offset(0);
//        make.height.offset(62);
//    }];
}

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


#pragma mark - 隐藏空间
- (void)showUI:(BOOL)success
{
    if (success) {
        self.backView.hidden = NO;
        self.backView_Name.hidden = NO;
        self.backView_IDNumber.hidden = NO;
        self.img_Example.hidden = NO;
        self.lb_Example.hidden = NO;
        self.lb_title.hidden = NO;
        self.leftLine.hidden = NO;
        self.rightLine.hidden = NO;
        self.btn_next.hidden = NO;
        
    }else{
        self.backView.hidden = YES;
        self.backView_Name.hidden = YES;
        self.backView_IDNumber.hidden = YES;
        self.img_Example.hidden = YES;
        self.lb_Example.hidden = YES;
        self.lb_title.hidden = YES;
        self.leftLine.hidden = YES;
        self.rightLine.hidden = YES;
        self.btn_next.hidden = YES;
    }
}

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




#pragma mark - SCNavigationControllerDelegate
- (void)sendIDCValue:(NSString *)name SEX:(NSString *)sex FOLK:(NSString *)folk BIRTHDAY:(NSString *)birthday ADDRESS:(NSString *) address NUM:(NSString *)num
{
    self.tf_Name.text =name;
    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.tf_IDNumber.text =  [NSString stringWithFormat:@"%@ %@ %@ %@",st1,st2,st3,st4];
    
}


#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 - event response
- (void)scanClick:(UIButton *)sendr
{
    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)nextStepClick:(UIButton *)sender
{
    if ([self.tf_Name.text length] <=0) {
        [SVProgressHUD showInfoWithStatus:@"请输入您的姓名!"];
        return;
    }
    NSString *newStr = [self.tf_IDNumber.text  stringByReplacingOccurrencesOfString:@" " withString:@""];
    BOOL IDCardInjudicious = [IDCardNumber_Validate isValidateIDCardString:newStr];
    if (!IDCardInjudicious) {
         [SVProgressHUD showErrorWithStatus:@"身份证上有格式上的错误"];
        return;
    }

    NSString *name=self.tf_Name.text;
    [self getSSCardSign:name:newStr];

    
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    [self.view endEditing:YES];
}


#pragma mark - OCR
-(void)getOCR
{
#if TARGET_IPHONE_SIMULATOR
    
#else
    // 打开引擎
    Gint ret = 0;
    Gint vaule = 1;
    ret = TREC_StartUP(TREC_GetEngineTimeKEY());
    if (ret == 100) {
        return;
    }
    if (ret == 100) {
        return;
    }if (ret == 101) {
        return;
    }
    
    ret = TREC_SetParam(T_SET_HEADIMG, &vaule);
    ret = TREC_SetSupportEngine(TIDCARD2);// 演示使用身份证，其他证件以此类推
    
    UIImage *sdfasf;
    sdfasf=   TREC_GetHeadImage();// 获取人头像图片流
    
    if (ret != 1) {
        
        TREC_ClearUP();
        return;
    }
    
    
    ret = TREC_ClearUP();
#endif
    
    
    
    
}

#pragma mark - 电子社保卡请求
-(void)queryCardResult
{
    NSString *url = [NSString stringWithFormat:@"%@card/local",SSCardBaseUrl];
    
    NSDictionary *params = @{
                             @"userId":[NSNumber numberWithInteger:[getPeopleID PeopleID]]
                             };
    
 
    [SVProgressHUD show];
    [CTAPIBaseManager POST:url params:params completionHandler:^(id  _Nonnull responseObject, NSError * _Nonnull error) {
        [SVProgressHUD dismiss];
        
        if (error) {
            NSLog(@"%@",error);
            [SVProgressHUD showInfoWithStatus:@"网络异常"];
            return;
            
        }
        
        if (responseObject) {
            NSLog(@"电子社保卡responseObject:%@",responseObject);
            if ([responseObject[@"code"] isKindOfClass:[NSNumber class]]) {
                NSNumber *code = responseObject[@"code"];
                if (code.integerValue == 200) {
                    //如果返回的字符串不为空
                    if (![NSString blankString:responseObject[@"result"]]) {
                        
                        
                        [self queryCard:responseObject[@"result"]];
                        
                        return;
                    }else{
                        [self showUI:YES];
                        [self alertMessage];
                    }
                }else{
                    [SVProgressHUD showInfoWithStatus:@"网络异常"];
                }
            }else{
                [SVProgressHUD showInfoWithStatus:@"服务端异常"];
            }
            
            
        }
        
    }];
}

- (void)queryCard:(NSString *)auth_no
{
    
    NSString *url = [NSString stringWithFormat:@"%@card/query",SSCardBaseUrl];
    
    NSDictionary *params = @{
                             @"auth_no":auth_no
                             };
    [SVProgressHUD show];
    [CTAPIBaseManager POST:url params:params completionHandler:^(id  _Nonnull responseObject, NSError * _Nonnull error) {
        [SVProgressHUD dismiss];
        
        if (error) {
            NSLog(@"%@",error);
            [SVProgressHUD showInfoWithStatus:@"网络异常"];
            return;
            
        }
        
        if (responseObject) {
            if ([responseObject[@"code"] isKindOfClass:[NSNumber class]]) {
                NSNumber *code = responseObject[@"code"];
                
                NSLog(@"%@",responseObject);
                if (code.integerValue == 200) {
                    //如果返回的字符串不为空
                    if (![NSString blankString:responseObject[@"result"]]) {
                        
                        NSDictionary *dic = [self dictionaryWithJsonString:responseObject[@"result"]];
                        if ([dic[@"alipay_commerce_app_upload_response"][@"code"] isEqualToString:@"10000"]) {
                            NSDictionary *dic2 = [self dictionaryWithJsonString:dic[@"alipay_commerce_app_upload_response"][@"data"][@"response"]];
                            if (![NSString blankString:dic2[@"outUserCardNo"]]) {
                                [self.view addSubview:self.frontView];
                                self.lb_name.text = dic2[@"outUserName"];
                                self.lb_cardId.text = dic2[@"outUserCardNo"];
                                return;
                            }
                            
                        }
                        [self showUI:YES];
                        [self alertMessage];
                        
                    }else{
                        [self showUI:YES];
                    }
                }else{
                    [self showUI:YES];
                }
            }else {
                [SVProgressHUD showInfoWithStatus:@"服务端异常"];
                return;
            }
            
           
            
        }
        
    }];
}


- (void)queryCard2:(NSString *)auth_no
{
    
    NSString *url = [NSString stringWithFormat:@"%@card/query",SSCardBaseUrl];
    
    NSDictionary *params = @{
                             @"auth_no":auth_no
                             };
    [SVProgressHUD show];
    [CTAPIBaseManager POST:url params:params completionHandler:^(id  _Nonnull responseObject, NSError * _Nonnull error) {
        [SVProgressHUD dismiss];
        
        if (error) {
            NSLog(@"%@",error);
            [SVProgressHUD showInfoWithStatus:@"网络异常"];
            return;
            
        }
        
        if (responseObject) {
            if ([responseObject[@"code"] isKindOfClass:[NSNumber class]]) {
                NSNumber *code = responseObject[@"code"];
                
                NSLog(@"%@",responseObject);
                if (code.integerValue == 200) {
                    //如果返回的字符串不为空
                    if (![NSString blankString:responseObject[@"result"]]) {
                        
                        NSDictionary *dic = [self dictionaryWithJsonString:responseObject[@"result"]];
                        if ([dic[@"alipay_commerce_app_upload_response"][@"code"] isEqualToString:@"10000"]) {
                            NSDictionary *dic2 = [self dictionaryWithJsonString:dic[@"alipay_commerce_app_upload_response"][@"data"][@"response"]];
                            if (![NSString blankString:dic2[@"outUserCardNo"]]) {
                                [self.view addSubview:self.frontView];
                                self.lb_name.text = dic2[@"outUserName"];
                                self.lb_cardId.text = dic2[@"outUserCardNo"];
                                return;
                            }
                            
                            
                            
                        }
                        
                        [self getBindUrlWithAuth_no:auth_no];
                        
//                        [self showUI:YES];
//                        [self alertMessage];
                        
                    }else{
                        [self showUI:YES];
                    }
                }else{
                    [self showUI:YES];
                }
            }else {
                [SVProgressHUD showInfoWithStatus:@"服务端异常"];
                return;
            }
            
           
            
        }
        
    }];
}

//提醒
- (void)alertMessage
{
    
    NSString*sstermination = [[NSUserDefaults standardUserDefaults]objectForKey:@"sstermination"];
    if (!sstermination) {
        [self createAlterController];
    }
}
/*** 弹出对话框 */
- (void)createAlterController
{
    UIAlertController *alter = [UIAlertController alertControllerWithTitle:@"提示信息" message:@"只能绑定本人电子社保卡" preferredStyle:UIAlertControllerStyleAlert];
    //确定按钮的风格是默认的
    UIAlertAction *sure = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        NSLog(@"确定");
        
        [[NSUserDefaults standardUserDefaults]setObject:@"yes" forKey:@"sstermination"];
        [[NSUserDefaults standardUserDefaults]synchronize];
        //添加你自己让他发生的事件  都是一样的！！！！！
    }];
    //取消按钮的风格是取消， 并且一直在最下边，且只能有一个
    
    [alter addAction:sure];
    [self presentViewController:alter animated:YES completion:^{
        
    }];
}

- (void)getSSCardSign:(NSString*) name:(NSString*) num{
    NSString *url = [[NSString stringWithFormat:@"%@/electronic/social/issuance/jbxSign",CSL_url]  stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
       //NSString *newStr = [self.tf_IDNumber.text  stringByReplacingOccurrencesOfString:@" " withString:@""];
    NSString *enName=[GMSm4Utils ecbEncryptText:name key:SMKey].lowercaseString;
    NSString *idNum=[GMSm4Utils ecbEncryptText:num key:SMKey].lowercaseString;
    NSString *phone=[GMSm4Utils ecbEncryptText:[getPeopleID PeopleIphoneNmber] key:SMKey].lowercaseString;
    NSDictionary *params = @{
                             @"userId":[NSNumber numberWithInteger:[getPeopleID PeopleID]],
                             @"name":enName,
                             @"idCard":idNum,
                             @"phone":phone
                             };
    [[NSUserDefaults standardUserDefaults]setObject:enName forKey:@"essCardName"];//保存name
    [[NSUserDefaults standardUserDefaults]setObject:idNum forKey:@"essCardIdNum"];//保存id
    [SVProgressHUD show];
    [NetworkRequest PostNomal:url Params:params Success:^(id _Nonnull objc) {
        NSString* state = [NSString stringWithFormat:@"%@",objc[@"state"]];
        [SVProgressHUD dismiss];
        if ([state isEqualToString:@"200"]) {
            NSDictionary *result=objc[@"result"];
            NSString* token = [NSString stringWithFormat:@"%@",result[@"token"]];//获取token
            [[NSUserDefaults standardUserDefaults]setObject:token forKey:@"essCardToken"];//保存token
            NSDictionary *data=result[@"data"];
            NSString* bindStatus = [NSString stringWithFormat:@"%@",data[@"bindStatus"]];//状态
            if([bindStatus isEqualToString:@"UNBIND"]||[bindStatus isEqualToString:@"BIND"]){//可申领
                NSString* returnUrl = [NSString stringWithFormat:@"%@",data[@"returnUrl"]];//社保卡url
                NSString *ess_token=[GMSm4Utils ecbDecryptText:returnUrl key:SMKey];
                NSString *url = [[SSCPublicHeader sharedSSCTool] webUrlWith:SSCServiceType_Main
                signStr:ess_token];
                [[SSCPublicHeader sharedSSCTool] presentWebVCFrom:self esscUrl:url
                esscDelegate:self];
            }else{//不可申领
                if ([[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:@"alipays://"]]) {
                    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"alipays://platformapi/startapp?appId=20000067&url=https%3A%2F%2Frender.alipay.com%2Fp%2Fs%2Fmedical-card-online%2Fwww%2Findex.html%3FchInfo%3DPDA01B01C01D00%26__webview_options__%3D"] options:nil completionHandler:nil];
                    return;
                }else{
                    if (![WXApi isWXAppInstalled]){
                        [Tools showMessage:@"请安装支付宝APP后重试"];
                        return;
                    }
                    WXLaunchMiniProgramReq *launchMiniProgramReq = [WXLaunchMiniProgramReq object];
                    launchMiniProgramReq.userName = @"gh_c02ba94d95e2";  //拉起的小程序的username
                    launchMiniProgramReq.path = @"pages/activity2/index/main?channel=AAEa8uDL_CLi4rjQ2mxeJFys";    //拉起小程序页面的可带参路径，不填默认拉起小程序首页
                    launchMiniProgramReq.miniProgramType = WXMiniProgramTypeRelease; //拉起小程序的类型
                    [WXApi sendReq:launchMiniProgramReq completion:^(BOOL success) {
                    }];
                }
            }
        }
    } Failure:^(NSError* error) {
        [SVProgressHUD dismiss];
        NSLog(@"error:%@",error);
    }];
    [self insertUserInfo:name :num];
}

- (void)insertUserInfo:(NSString *)name:(NSString*) number{
    if (![self queryDataExist:name :number]) {
        FMDatabase *db = [FMDatabase databaseWithPath:[self getDBPath]];

        if ([db open]) {
            
            NSString *sql = [NSString stringWithFormat:@"SELECT Count(1) FROM t_rzUserSBCard WHERE userid='%ld' ",[getPeopleID PeopleID]];
            NSUInteger count  = [db intForQuery:sql];
            NSLog(@"已添加数据:%ld",count);
            if (count >= 5) {
                
            NSString *sql2 = [NSString stringWithFormat:@"SELECT  id FROM t_rzUserSBCard WHERE userid='%ld' LIMIT 1  ;",[getPeopleID PeopleID]];
             NSInteger Id = [db intForQuery:sql2];
                
              NSString *sql3 = [NSString stringWithFormat:@"delete from t_rzUserSBCard where id = '%ld'",Id];
              BOOL reslut =   [db executeUpdate:sql3];
                if (reslut) {
                    NSString * sql4 = [NSString stringWithFormat:@"INSERT INTO t_rzUserSBCard (name,idNumber,userid,timeSp) VALUES (?, ?,?,?);"];
                    NSString *userid = [NSString stringWithFormat:@"%ld",[getPeopleID PeopleID]];
                    NSString *timeSp = [NSString stringWithFormat:@"%ld",[self getNowTimeTimestamp3]];
                    
                    BOOL res =  [db executeUpdate:sql4,name,number,userid,timeSp];
                    

                    if (!res) {
                        NSLog(@"error to insert data");
                    }else{
                        NSLog(@"success to insert data");
                    }
                }
            }else{
                NSString * sql4 = [NSString stringWithFormat:@"INSERT INTO t_rzUserSBCard (name,idNumber,userid,timeSp) VALUES (?, ?,?,?);"];
                NSString *userid = [NSString stringWithFormat:@"%ld",[getPeopleID PeopleID]];
                NSString *timeSp = [NSString stringWithFormat:@"%ld",[self getNowTimeTimestamp3]];
                BOOL res =  [db executeUpdate:sql4,name,number,userid,timeSp];
               if (!res) {
                   NSLog(@"error to insert data");
               }else{
                   NSLog(@"success to insert data");
               }
            }
            
            [db close];
        }
    }else{
        FMDatabase *db = [FMDatabase databaseWithPath:[self getDBPath]];
         NSString *timeSp = [NSString stringWithFormat:@"%ld",[self getNowTimeTimestamp3]];
        if ([db open]) {
            NSString *sql = @"UPDATE t_rzUserSBCard SET timeSp = ? WHERE  idNumber = ?";
            BOOL res = [db executeUpdate:sql, timeSp, number];
            if (!res) {
                       NSLog(@"error to UPDATE data");
            }else {
                       NSLog(@"success to UPDATE data");
                      
            }
            [db close];
        }
    }
    
}

#pragma mark - 创建本地数据库
- (BOOL)queryDataExist:(NSString *)name:(NSString*) number{
    
//    self.name = @"徐振东";
//    self.idNumber = @"110101199003075576";
//        self.name = @"小慧";
//        self.idNumber = @"110101199003077192";
    FMDatabase *db = [FMDatabase databaseWithPath:[self getDBPath]];
    if ([db open]){
        NSString *sql = [NSString stringWithFormat:@"SELECT * FROM t_rzUserSBCard WHERE userid='%@'  and idNumber='%@';",[NSString stringWithFormat:@"%ld",[getPeopleID PeopleID]],number];
        FMResultSet *resultSet = [db executeQuery:sql];
        
        if (resultSet.next) {
            [db close];
            return YES;
        }else{
            [db close];
            return NO;
        }
    }
    [db close];
    return YES;
}
#pragma mark - 获取当前时间戳
-(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;
}

- (void)backResponseResult:(NSString *)responseResult{
    NSLog(@"%@",responseResult);
    NSDictionary *dic = [NSDictionary dictionaryWithJsonString:responseResult];
    NSString *actionType = dic[@"actionType"];
    NSString *signNo=[GMSm4Utils ecbEncryptText:dic[@"signNo"] key:SMKey].lowercaseString;
    NSString *busiSeq=[GMSm4Utils ecbEncryptText:dic[@"busiSeq"] key:SMKey].lowercaseString;

    if ([actionType isEqualToString:@"001"]||[actionType isEqualToString:@"002"]) {//申领 和 当前渠道签发状态更新
        [self essUpdateStatus:@"BIND" signNo:signNo busiSeq:busiSeq type:@"3"];
    }else if([actionType isEqualToString:@"003"]){//解绑
        [self essUpdateStatus:@"UNBIND" signNo:signNo busiSeq:busiSeq type:@"3"];
    }else if([actionType isEqualToString:@"014"]){//待遇认证
        [self essAuthResult];
    }
}
-(void) essAuthResult {
    NSString *url = [[NSString stringWithFormat:@"%@/electronic/social/certification/saveCertification",CSL_url] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSString * phone=[GMSm4Utils ecbEncryptText:[getPeopleID PeopleIphoneNmber] key:SMKey].lowercaseString;
    NSString *name=[[NSUserDefaults standardUserDefaults]stringForKey:@"essCardName"];//name
    NSString *idNum=[[NSUserDefaults standardUserDefaults]stringForKey:@"essCardIdNum"];//id
    NSDictionary *params = @{
                             @"userId":[NSNumber numberWithInteger:[getPeopleID PeopleID]],
                             @"name":name,
                             @"idCard":idNum,
                             @"phone":phone
                             };
    [NetworkRequest PostEssResult:url Params:params Success:^(id _Nonnull objc) {
        if ([objc isKindOfClass:[NSDictionary class]]) {
            NSString *state = [NSString stringWithFormat:@"%@",objc[@"state"]];
            if ([state isEqualToString:@"200"]) {
                NSLog(@"%@",@"电子认证状态:更新成功!");
            }else if ([state isEqualToString:@"50009"]){//token过期
                NSString *refreshToken = [[NSString stringWithFormat:@"%@/electronic/social/issuance/refreshToken",CSL_url] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
                [NetworkRequest PostEssResult:refreshToken Params:params Success:^(id _Nonnull obj){
                    if ([obj isKindOfClass:[NSDictionary class]]) {
                        NSString *tokenstate = [NSString stringWithFormat:@"%@",obj[@"state"]];
                        if ([tokenstate isEqualToString:@"200"]) {
                            NSString *newToken=obj[@"result"];
                            [[NSUserDefaults standardUserDefaults]setObject:newToken forKey:@"essCardToken"];//保存token
                            [self essAuthResult];
                        }
                    }
                } Failure:^(NSError *error) {
                    NSLog(@"error:%@",error);
                }];
            }
            
        }
    } Failure:^(NSError *error) {
        NSLog(@"error:%@",error);
    }];
}

-(void) essUpdateStatus:(NSString *)status signNo:(NSString *)signNo  busiSeq:(NSString *)busiSeq type:(NSString *)type {
    NSString *url = [[NSString stringWithFormat:@"%@/electronic/social/issuance/updateSign",CSL_url] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSString * phone=[GMSm4Utils ecbEncryptText:[getPeopleID PeopleIphoneNmber] key:SMKey].lowercaseString;
    NSString *name=[[NSUserDefaults standardUserDefaults]stringForKey:@"essCardName"];//name
    NSString *idNum=[[NSUserDefaults standardUserDefaults]stringForKey:@"essCardIdNum"];//id
    NSDictionary *params = @{
                             @"userId":[NSNumber numberWithInteger:[getPeopleID PeopleID]],
                             @"name":name,
                             @"idCard":idNum,
                             @"phone":phone,
                             @"status":status,
                             @"signNo":signNo,
                             @"busiSeq":busiSeq,
                             @"type": type,
                             @"remark":@"朋友",
                             @"province":[GMSm4Utils ecbEncryptText:@"" key:SMKey].lowercaseString
                             };
    [NetworkRequest PostEssResult:url Params:params Success:^(id _Nonnull objc) {
        if ([objc isKindOfClass:[NSDictionary class]]) {
            NSString *state = [NSString stringWithFormat:@"%@",objc[@"state"]];
            if ([state isEqualToString:@"200"]) {
                NSLog(@"%@",@"签发状态:更新成功!");
                //[Tools showMessage:[NSString stringWithFormat:@"%@,",@"更新成功"]];
            }else if ([state isEqualToString:@"50009"]){//token过期
                NSString *refreshToken = [[NSString stringWithFormat:@"%@/electronic/social/issuance/refreshToken",CSL_url] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
                [NetworkRequest PostEssResult:refreshToken Params:params Success:^(id _Nonnull obj){
                    if ([obj isKindOfClass:[NSDictionary class]]) {
                        NSString *tokenstate = [NSString stringWithFormat:@"%@",obj[@"state"]];
                        if ([tokenstate isEqualToString:@"200"]) {
                            NSString *newToken=obj[@"result"];
                            [[NSUserDefaults standardUserDefaults]setObject:newToken forKey:@"essCardToken"];//保存token
                            [self essUpdateStatus:status signNo:signNo busiSeq:busiSeq type:type];
                        }
                    }
                } Failure:^(NSError *error) {
                    NSLog(@"error:%@",error);
                }];
            }
        }
    } Failure:^(NSError *error) {
        NSLog(@"error:%@",error);
        [Tools showMessage:[NSString stringWithFormat:@"%@,",error]];
    }];
    
}




- (void)getBindUrlWithAuth_no:(NSString *)auth_no
{
    NSString *url = [NSString stringWithFormat:@"%@/card/bind",SSCardBaseUrl];
    
    NSDictionary *params = @{
                             @"auth_no":auth_no,
                             };
    
    [CTAPIBaseManager POST:url params:params completionHandler:^(id  _Nonnull responseObject, NSError * _Nonnull error) {
        
        if (error) {
            NSLog(@"%@",error);
            [SVProgressHUD showInfoWithStatus:@"网络异常"];
            return;
            
        }
        
        if ([responseObject[@"code"] isKindOfClass:[NSNumber class]]) {
            if (responseObject) {
                NSNumber *code = responseObject[@"code"];
//                NSString *msg = responseObject[@"msg"];
                
                NSLog(@"%@",responseObject);
                if (code.integerValue == 200) {
                    
                    [SVProgressHUD dismiss];
                    
                    
                    id result = responseObject[@"result"];
                    if ([result isKindOfClass:[NSString class]] && ![NSString blankString:result]) {
                        NSString *res = result;
                        NSString *dataStr =[SecurityUtil decodeBase64String:res];
                        
                        [self jumpToHTML5:dataStr andJAnalytics:@"电子社保卡" JSString:dataStr];
                        
                        
                        
                    }
                    
                    
                    
                }else{
                    [SVProgressHUD showInfoWithStatus:@"网络异常"];
                    return;
                }
            }
        }else {
            [SVProgressHUD showInfoWithStatus:@"服务端异常"];
            return;
        }
        
      
        
    }];
}



#pragma mark - private methods

-(void)jumpToHTML5:(NSString*)url andJAnalytics:(NSString*)janalytics JSString:(NSString *)jsString
{
    WebViewController *tc=[WebViewController new];
    tc.hidesBottomBarWhenPushed =YES;
    tc.URL = [NSURL URLWithString:url];
    tc.janalytics = janalytics;
    tc.jsString = jsString;
    [self.navigationController pushViewController:tc animated:YES];
    
}
/// 添加四边阴影效果
- (void)addShadowToView:(UIView *)theView withColor:(UIColor *)theColor {
    // 阴影颜色
    theView.layer.shadowColor = theColor.CGColor;
    // 阴影偏移，默认(0, -3)
    theView.layer.shadowOffset = CGSizeMake(0,0);
    // 阴影透明度，默认0
    theView.layer.shadowOpacity = 0.5;
    // 阴影半径，默认3
    theView.layer.shadowRadius = 3;
    
}

- (NSDictionary *)dictionaryWithJsonString:(NSString *)jsonString {
    
    if (jsonString == nil) {
        
        return nil;
        
        
        
    }
    
    
    
    NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
    
    NSError *err;
    
    NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData
                         
                                                        options:NSJSONReadingMutableContainers
                         
                                                          error:&err];
    
    if(err) {
        
        NSLog(@"json解析失败：%@",err);
        
        return nil;
        
    }
    
    return dic;
    
}

#pragma mark - getters and setters

- (XZDrawView *)backView
{
    if (!_backView ) {
        _backView = [[XZDrawView alloc]initWithFrame:CGRectMake(0, cl_kNavigationBarHeight, ScreenWidth, 370 * WIDTHRADIU)];
        _backView.backgroundColor = [UIColor whiteColor];
         
    }
    return _backView;
}
- (UIView *)backView_Name
{
    if (!_backView_Name) {
        _backView_Name = [[UIView alloc]init];
        _backView_Name.backgroundColor = [UIColor clearColor];
        [self addShadowToView:_backView_Name withColor:K_MainColor];
        [_backView_Name addSubview:self.view_Name];
    }
    return _backView_Name;
}
- (UIView *)view_Name
{
    if (!_view_Name) {
        _view_Name = [[UIView alloc]init];
        _view_Name.backgroundColor = [UIColor whiteColor];
        _view_Name.layer.cornerRadius = 5 * WIDTHRADIU;
        _view_Name.layer.masksToBounds = YES;
        [_view_Name addSubview:self.subView_Name];
        [_view_Name addSubview:self.tf_Name];
    }
    return _view_Name;
}

- (UIView *)subView_Name
{
    if (!_subView_Name) {
        _subView_Name = [[UIView alloc]init];
        _subView_Name.backgroundColor = K_MainColor;
        CAGradientLayer *gradientLayer =  [CAGradientLayer layer];
        gradientLayer.frame = CGRectMake(0, 0, 65 * WIDTHRADIU, 45 * WIDTHRADIU);
        gradientLayer.startPoint = CGPointMake(0, 1);
        gradientLayer.endPoint = CGPointMake(1, 0);
        //gradientLayer.locations = @[@(0),@(0.5)];//渐变点
        [gradientLayer setColors:@[(id)[[UIColor colorWithHex:0x2895f7] CGColor],(id)[[UIColor colorWithHex:0x1fa9e1] CGColor]]];//渐变数组
        [_subView_Name.layer addSublayer:gradientLayer];
        [_subView_Name addSubview:self.img_Name];
    }
    return _subView_Name;
}

- (UIImageView *)img_Name
{
    if (!_img_Name) {
        _img_Name = [[UIImageView alloc]init];
        _img_Name.image = [UIImage imageNamed:@"my_Socialsecuritytermination_deathcertificate_Name_normal"];
    }
    return _img_Name;
}

- (UITextField *)tf_Name
{
    if (!_tf_Name) {
        _tf_Name = [[UITextField alloc]init];
        _tf_Name.placeholder = @"请输入姓名";
        _tf_Name.borderStyle =  UITextBorderStyleNone;
        _tf_Name.backgroundColor = [UIColor clearColor];
        _tf_Name.delegate = self;
    }
    return _tf_Name;
}


- (UIView *)backView_IDNumber
{
    if (!_backView_IDNumber) {
        _backView_IDNumber = [[UIView alloc]init];
        _backView_IDNumber.backgroundColor = [UIColor clearColor];
        [self addShadowToView:_backView_IDNumber withColor:K_MainColor];
        [_backView_IDNumber addSubview:self.view_IDNumber];
    }
    return _backView_IDNumber;
}
- (UIView *)view_IDNumber
{
    if (!_view_IDNumber) {
        _view_IDNumber = [[UIView alloc]init];
        _view_IDNumber.backgroundColor = [UIColor whiteColor];
        _view_IDNumber.layer.cornerRadius = 5 * WIDTHRADIU;
        _view_IDNumber.layer.masksToBounds = YES;
        [_view_IDNumber addSubview:self.subView_IDNumber];
        [_view_IDNumber addSubview:self.tf_IDNumber];
        [_view_IDNumber addSubview:self.btn_scan];
    }
    return _view_IDNumber;
}

- (UIView *)subView_IDNumber
{
    if (!_subView_IDNumber) {
        _subView_IDNumber = [[UIView alloc]init];
        _subView_IDNumber.backgroundColor = K_MainColor;
        CAGradientLayer *gradientLayer =  [CAGradientLayer layer];
        gradientLayer.frame = CGRectMake(0, 0, 65 * WIDTHRADIU, 45 * WIDTHRADIU);
        gradientLayer.startPoint = CGPointMake(0, 1);
        gradientLayer.endPoint = CGPointMake(1, 0);
        //gradientLayer.locations = @[@(0),@(0.5)];//渐变点
        [gradientLayer setColors:@[(id)[[UIColor colorWithHex:0x2895f7] CGColor],(id)[[UIColor colorWithHex:0x1fa9e1] CGColor]]];//渐变数组
        [_subView_IDNumber.layer addSublayer:gradientLayer];
        [_subView_IDNumber addSubview:self.img_IDNumber];
    }
    return _subView_IDNumber;
}

- (UIImageView *)img_IDNumber
{
    if (!_img_IDNumber) {
        _img_IDNumber = [[UIImageView alloc]init];
        _img_IDNumber.image = [UIImage imageNamed:@"my_Socialsecuritytermination_deathcertificate_IDnumber_normal"];
    }
    return _img_IDNumber;
}

- (UITextField *)tf_IDNumber
{
    if (!_tf_IDNumber) {
        _tf_IDNumber = [[UITextField alloc]init];
        _tf_IDNumber.placeholder = @"请输入身份证号";
        _tf_IDNumber.borderStyle =  UITextBorderStyleNone;
        _tf_IDNumber.backgroundColor = [UIColor clearColor];
        _tf_IDNumber.delegate = self;
    }
    return _tf_IDNumber;
}

- (UIButton *)btn_scan
{
    if (!_btn_scan) {
        _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];
    }
    return _btn_scan;
}

- (UILabel *)lb_Example
{
    if (!_lb_Example ) {
        _lb_Example = [[UILabel alloc]init];
        _lb_Example.text = @"例:";
        _lb_Example.font = [UIFont systemFontOfSize:19 * WIDTHRADIU];
        _lb_Example.textColor = [UIColor colorWithHex:0xb3b3b3];
    }
    return _lb_Example;
}

- (UIImageView  *)img_Example
{
    if (!_img_Example) {
        _img_Example = [[UIImageView alloc]init];
        _img_Example.image = [UIImage imageNamed:@"身份证图"];
    }
    return _img_Example;
}

- (UIImageView  *)video_Example
{
    if (!_video_Example) {
        _video_Example = [[UIImageView alloc]init];
        _video_Example.image = [UIImage imageNamed:@"authVideo"];
        _video_Example.userInteractionEnabled = YES;
        UITapGestureRecognizer* tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(watchClick:)];
        [_video_Example addGestureRecognizer:tap];
    }
    return _video_Example;
}

- (void)watchClick:(UITapGestureRecognizer *)ges {
    WebVC *vc = [[WebVC alloc]init];
    vc.title = @"教学视频";
    vc.url = @"http://nginx.weface.com.cn/appH5/Mp4/dzsbk.html";
    [self.navigationController pushViewController:vc animated:YES];
}

- (UILabel *)lb_title
{
    if (!_lb_title) {
        _lb_title = [[UILabel alloc]init];
        _lb_title.font = [UIFont systemFontOfSize:14 * WIDTHRADIU];
        //_lb_title.text = @"拍摄身份证，自动录入信息";
        _lb_title.textColor = [UIColor colorWithHex:0xb3b3b3];
        _lb_title.textAlignment = NSTextAlignmentCenter;
    }
    return _lb_title;
}

- (UIView *)leftLine
{
    if (!_leftLine) {
        _leftLine = [[UIView alloc]init];
        //_leftLine.backgroundColor = [UIColor colorWithHex:0xb3b3b3];
    }
    return _leftLine;
}

- (UIView *)rightLine
{
    if (!_rightLine) {
        _rightLine = [[UIView alloc]init];
        //_rightLine.backgroundColor = [UIColor colorWithHex:0xb3b3b3];
    }
    return _rightLine;
}

- (UIButton *)btn_next{
    if (!_btn_next) {
        _btn_next = [UIButton buttonWithType:UIButtonTypeCustom];
        CAGradientLayer *gradientLayer =  [CAGradientLayer layer];
        gradientLayer.frame = CGRectMake(0, 0, ScreenWidth - 35 * WIDTHRADIU, 45 * WIDTHRADIU);
        gradientLayer.startPoint = CGPointMake(0, 0);
        gradientLayer.endPoint = CGPointMake(1, 0);
        //gradientLayer.locations = @[@(0),@(0.5)];//渐变点
        [gradientLayer setColors:@[(id)[[UIColor colorWithHex:0x2794f6] CGColor],(id)[[UIColor colorWithHex:0x1fabe1] CGColor]]];//渐变数组
        [_btn_next.layer addSublayer:gradientLayer];
        [_btn_next setTitle:@"申领电子社保卡" forState:UIControlStateNormal];
        [_btn_next setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        _btn_next.titleLabel.font = [UIFont systemFontOfSize:16 * WIDTHRADIU];
       
        
        _btn_next.layer.cornerRadius = 10;
        _btn_next.layer.masksToBounds = YES;
        [_btn_next addTarget:self action:@selector(nextStepClick:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _btn_next;
}

- (UIView *)frontView
{
    if (!_frontView) {
        _frontView = [[UIView alloc]initWithFrame:CGRectMake(0, cl_kNavigationBarHeight, ScreenWidth, ScreenHeight - cl_kNavigationBarHeight)];
        _frontView.backgroundColor = [UIColor whiteColor];
        [_frontView addSubview:self.img_back];
        [_frontView addSubview:self.lb_name];
        [_frontView addSubview:self.lb_cardId];
        UIImage *image = [UIImage imageNamed:@"电子社保卡"];
        CGFloat scale = image.size.height/image.size.width;
        [self.img_back mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.offset(25 * WIDTHRADIU);
            make.right.offset(-25 * WIDTHRADIU);
            make.top.offset(15 * WIDTHRADIU);
            make.height.offset((ScreenWidth - 50 * WIDTHRADIU) * scale);
        }];
        [self.lb_name mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.offset(105 * WIDTHRADIU);
            make.left.offset(50 * WIDTHRADIU);
            make.height.offset(15 * WIDTHRADIU);
        }];
        
        [self.lb_cardId mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(self.lb_name.mas_bottom).offset(10 * WIDTHRADIU);
            make.left.equalTo(self.lb_name);
            make.height.offset(15 * WIDTHRADIU);
        }];
    }
    return _frontView;
}

- (UIImageView *)img_back
{
    if (!_img_back) {
        _img_back = [[UIImageView alloc]init];
        _img_back.image = [UIImage imageNamed:@"电子社保卡"];
    }
    return _img_back;
}

- (UILabel *)lb_name
{
    if (!_lb_name) {
        _lb_name = [[UILabel alloc]init];
        _lb_name.text = @"姓       名:";
        _lb_name.textColor = [UIColor colorWithHex:0x0a457a];
        _lb_name.font = [UIFont systemFontOfSize:15 * WIDTHRADIU];
    }
    return _lb_name;
}

- (UILabel *)lb_cardId
{
    if (!_lb_cardId) {
        _lb_cardId  = [[UILabel alloc]init];
        _lb_cardId.text = @"社保卡号:";
        _lb_cardId.textColor = [UIColor colorWithHex:0x0a457a];
        _lb_cardId.font = [UIFont systemFontOfSize:15 * WIDTHRADIU];
    }
    return _lb_cardId;
}




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