//
//  DistrictAuthenticationPersonalInfoController.m
//  KKCivilAd
//
//  Created by 雷俊博 on 2019/11/25.
//  Copyright © 2019 雷俊博. All rights reserved.
//

#import "DistrictAuthenticationPersonalInfoController.h"
#import "NetworkTokenRequest.h"
#import "DistrictAuthPersonalInfoModel.h"

#import "DistrictAuthenticationInfoController.h"
#import "SSTerminationViewController.h"

//#import "AuthenticationListViewController.h"
#import "kankanshebaoxieyi.h"


#import "rzUserModel.h"
#import "RZUserCollectionViewCell.h"
#import "RZBottomCell.h"

#import "UIView+frameAdjust.h"

#import "Globaltypedef.h"
#if TARGET_IPHONE_SIMULATOR == 0
#import "SCCaptureCameraController.h"
#endif


//优抚核查认证记录
#import "AuthenticationListViewController.h"

#import "KKUserAuthViewController.h"

#import "KKAuthWhiteAlertView.h"

@interface DistrictAuthenticationPersonalInfoController ()
#if TARGET_IPHONE_SIMULATOR == 0
   <UITextFieldDelegate,SCNavigationControllerDelegate,UICollectionViewDelegate,UICollectionViewDataSource>
#endif
{
    UICollectionView* _mainCollectionView;
    UILabel*          _lb_message;
    UIView*           _leftLine;
    UIView*           _rightLine;
    
    DistrictAuthPersonalInfoModel* model;
    
    rzUserModel* userModel;
}
@property (nonatomic, strong)UIScrollView* scrollView;



//圆弧
@property (nonatomic, strong)UIImageView* topCircleImg;

//白色悬浮块
@property (nonatomic, strong)UIView* whiteView;

//姓名输入框背景图片
@property (nonatomic, strong)UIImageView* nameImg;
//姓名输入框
@property (nonatomic, strong)UITextField*nameText;
//身份证输入框
@property (nonatomic, strong)UITextField*IDText;

@property (nonatomic, strong)UIView* hideView;

@property (nonatomic, strong)UIButton* messageBtn;

@property (nonatomic, strong)UIButton* button_xieyi;

@property (nonatomic, strong)UIButton* PhotoBtn;

@property (nonatomic, strong)UIButton* agressBtn;

@property (nonatomic, strong)NSMutableArray* dataArray;


@property (nonatomic, strong)UICollectionView* collectionView;

//背景灰色
@property (nonatomic, strong)UIView*backImgView;
@property (nonatomic, strong)UIImageView*topBg;

@property (nonatomic, strong)UIImageView*videoImage;

@property (nonatomic, strong)UIView*clearView;

@property (nonatomic, strong)UIImageView*cardImage;

@property (nonatomic, strong)UIButton* cardBtn;


@property (weak, nonatomic) IBOutlet UIImageView *backImg_name;
@property (weak, nonatomic) IBOutlet UIImageView *backImg_Id;
@property (weak, nonatomic) IBOutlet UITextField *tf_name;
@property (weak, nonatomic) IBOutlet UITextField *tf_IdCard;
//@property (weak, nonatomic) IBOutlet UILabel *lb_message;

@end

@implementation DistrictAuthenticationPersonalInfoController

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:YES animated:animated];
    
    
    if ([self.type isEqualToString:@"butie"]) {
        @try {
            //此处写可能出现崩溃的代码
            //数组插入nil对象
            //[self showUser];
            [self creatTable2];
        } @catch (NSException *exception) {
            //捕获到异常要执行的代码
            NSLog(@"exc == %@, 最后我弹了一个弹框说这样不合适",exception);
        } @finally {
            //不管能不能捕获到异常都会执行的方法
            NSLog(@"最后");
        }
        [GTCountSDK trackCountEvent:@"home_BTAuth_commitInfoPage" withArgs:@{}];
    }else{
        
        [GTCountSDK trackCountEvent:@"home_YFAuth_commitInfoPage" withArgs:@{}];
        
        @try {
            //此处写可能出现崩溃的代码
            //数组插入nil对象
            //[self showUser];
            [self creatTable];
        } @catch (NSException *exception) {
            //捕获到异常要执行的代码
            NSLog(@"exc == %@, 最后我弹了一个弹框说这样不合适",exception);
        } @finally {
            //不管能不能捕获到异常都会执行的方法
            NSLog(@"最后");
        }
    }
    
    
    
}

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

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

- (void)configUI
{
    
    if (self.view.bounds.size.width > 320) {
        UIEdgeInsets insets = UIEdgeInsetsMake(0, 72.5, 0, 0);
        UIImage *backImgName = [UIImage imageNamed:@"社保认证姓名"];
        UIImage *backImgId = [UIImage imageNamed:@"社保认证身份证"];
        backImgName = [backImgName resizableImageWithCapInsets:insets resizingMode:UIImageResizingModeStretch];
        backImgId = [backImgId resizableImageWithCapInsets:insets resizingMode:UIImageResizingModeStretch];
        self.backImg_name.image = backImgName;
        self.backImg_Id.image = backImgId;
    }
    
    NSString*authMessage = [[NSUserDefaults standardUserDefaults]objectForKey:@"authdec"];

    if (![Tools isBlankString:authMessage]) {
        self.hideView.hidden = NO;
        [self.messageBtn setTitle:authMessage forState:UIControlStateNormal];
    }
    
}

- (void)configNav
{
   UIView*nav = [[UIView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, cl_kNavigationBarHeight)];
    nav.backgroundColor = K_MainColor;
    [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(cl_kNavBarHeight);
    }];
    
    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(cl_kNavBarHeight);
    }];
}

- (void)creatBottomView
{
    CGFloat height = 49;
    if (cl_kNavigationBarHeight > 64) {
        height = 83;
    }
    
    UIView*view = [[UIView alloc]initWithFrame:CGRectMake(0, ScreenHeight - height - 5 , ScreenWidth, 49 + 5)];
    view.backgroundColor = [UIColor whiteColor];
    
    UIView*line = [[UIView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, 0.5)];
    line.backgroundColor = [UIColor colorWithHex:0x4d4d4d];
    
    
    [self.view addSubview:view];
    
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
     // 设置item的行间距和列间距
    layout.minimumInteritemSpacing = 0;
    layout.minimumLineSpacing = 0;
    layout.scrollDirection = UICollectionViewScrollDirectionVertical;
    
    UICollectionView*collectionView = [[UICollectionView alloc]initWithFrame:CGRectMake(0, 5, ScreenWidth, 49) collectionViewLayout:layout];
    collectionView.backgroundColor = [UIColor whiteColor];
    collectionView.showsVerticalScrollIndicator = NO;   //是否显示滚动条
    collectionView.scrollEnabled = YES;  //滚动使能
    collectionView.delegate = self;
    collectionView.dataSource = self;
    [collectionView registerNib:[UINib nibWithNibName:@"RZBottomCell" bundle:nil] forCellWithReuseIdentifier:@"userCell"];
     
     self.collectionView = collectionView;
    [view addSubview:self.collectionView];
    [view addSubview:line];
    
    
//    collectionView.layer.borderWidth = 0.5;
//    collectionView.layer.borderColor = [UIColor colorWithHex:0xd4d4d4].CGColor;
    
   
}

#pragma mark - public methods
- (void)cleartText
{
    self.nameText.text = @"";
    self.IDText.text = @"";
}


#pragma mark - request api
- (NSDictionary *)requestParam:(NSInteger)index
{
    NSDictionary *params = nil;
    if (index == 100) {
        NSString*idText = [self.IDText.text stringByReplacingOccurrencesOfString:@" " withString:@""];
        idText = [idText uppercaseString];
        params= @{
            @"idcard":idText ? [EnercryTool AES256Encrypt:idText key:MZAESKEY] :@""
        };
    }else if (index == 101){
        
        
        NSString*idText = [userModel.idNumber stringByReplacingOccurrencesOfString:@" " withString:@""];
        idText = [userModel.idNumber uppercaseString];
       params= @{
           @"idcard":idText ? [EnercryTool AES256Encrypt:idText key:MZAESKEY] :@""
        };
    }
    return params;
}

- (void)queryPersonalInfoRequest:(NSInteger)index
{
    
    if ([self.type isEqualToString:@"butie"]) {
        [self butieQuery:index];
    }else{
        [self youfuQuery:index];
    }
   
}

- (void)youfuQuery:(NSInteger)index{
    WeakSelf
    NSString *urlString = [NSString stringWithFormat:@"%@%@",[NetworkConfig ipYouFuVerityConfig],CheckPersonalInfoRequest];
    NSLog(@"民政认证基本信息查询url:%@",urlString);
    NSLog(@"params:%@",[self requestParam:index]);
    
    NSString *token = [UserDefault objectForKey:@"token"];
    
    [KKLoadingAnimationView show];
    [NetworkRequest Get5:urlString Params:[self requestParam:index] Token:token Success:^(id  _Nonnull responseObject) {
        
        NSLog(@"responseObject:%@",responseObject);
        if ([responseObject isKindOfClass:[NSDictionary class]]) {
                NSString *state = [NSString stringWithFormat:@"%@",responseObject[@"state"]];
                NSString *describe = responseObject[@"describe"];
                if ([state isEqualToString:@"200"]) {
                    if ([responseObject[@"result"] isKindOfClass:[NSDictionary class]]) {
                        NSString * code = [NSString stringWithFormat:@"%@",responseObject[@"result"][@"code"]];
                        NSString *desc = responseObject[@"result"][@"desc"];
                        //
                        if ([code isEqualToString:@"200000"]) {
                            if ([responseObject[@"result"][@"data"] isKindOfClass:[NSDictionary class]]) {
                                self->model = [DistrictAuthPersonalInfoModel mj_objectWithKeyValues:responseObject[@"result"][@"data"]];
                                NSString*name = [EnercryTool AES256Decrypt:self->model.personName key:MZAESKEY];
                                name = [name stringByReplacingOccurrencesOfString:@" " withString:@""];
                                NSString*nameText = nil;
                                if (index == 100) {
                                    nameText = [self.nameText.text stringByReplacingOccurrencesOfString:@" " withString:@""];
                                }else if (index == 101){
                                    nameText = [userModel.name stringByReplacingOccurrencesOfString:@" " withString:@""];
                                }
                                if ([name isEqualToString:nameText]) {
                                    DistrictAuthenticationInfoController *vc = [Storyboard instantiateViewControllerWithIdentifier:@"DistrictAuthenticationInfoController"];
                                    vc.title = @"优抚对象信息";
                                    vc.model = self->model;
                                    vc.type = self.type;
                                    [self.navigationController pushViewController:vc animated:YES];
                                }else{
                                    [SVProgressHUD showInfoWithStatus:@"请输入正确的姓名"];
                                }
                                
                              
                            }
                            
                        }else if ([code isEqualToString:@"200003"]){
                            [self alertShow:@"用户不存在"];
                        }else if ([code isEqualToString:@"200004"]){
                            [self alertShow:@"不在认证期"];
                        }else if ([code isEqualToString:@"200005"]){
                            [self alertShow:@"已认证"];
                        }else if ([code isEqualToString:@"200006"]){
                            [self alertShow:@"状态异常无法认证"];
                        }else if ([code isEqualToString:@"200007"]){
                            
                            [self judgeAccountAuthStateRequest];
                            
                            return;
                        } else{
                            [self alertShow:desc];
                        }
                    }
                    
                    
                }else if ([state isEqualToString:@"700"]){
                    [weakSelf reloadData];
                    
                    return;
                }else{
                    [self alertShow:describe];
                }
                   
               }else{
                   [self alertShow:@"服务器异常"];
               }
        
        [KKLoadingAnimationView dismiss];
    } Failure:^(NSError * _Nonnull error) {
        [KKLoadingAnimationView dismiss];
        NSLog(@"error:%@",error);
    }];
}

- (void)butieQuery:(NSInteger)index
{
//    WeakSelf
    NSString *urlString = [NSString stringWithFormat:@"%@%@",[NetworkConfig ipYouFuVerityConfig],CheckPersonalInfoRequest];
    NSLog(@"民政认证基本信息查询url:%@",urlString);
    NSLog(@"params:%@",[self requestParam:index]);
    
    NSString *token = [UserDefault objectForKey:@"token"];
    
    [KKLoadingAnimationView show];
    [NetworkRequest Get6:urlString Params:[self requestParam:index] Token:token Success:^(id  _Nonnull responseObject) {
        
        NSLog(@"responseObject:%@",responseObject);
        if ([responseObject isKindOfClass:[NSDictionary class]]) {
                NSString *state = [NSString stringWithFormat:@"%@",responseObject[@"state"]];
                NSString *describe = responseObject[@"describe"];
                if ([state isEqualToString:@"200"]) {
                    if ([responseObject[@"result"] isKindOfClass:[NSDictionary class]]) {
                        NSString * code = [NSString stringWithFormat:@"%@",responseObject[@"result"][@"code"]];
                        NSString *desc = responseObject[@"result"][@"desc"];
                        //
                        if ([code isEqualToString:@"200000"]) {
                            if ([responseObject[@"result"][@"data"] isKindOfClass:[NSDictionary class]]) {
                                self->model = [DistrictAuthPersonalInfoModel mj_objectWithKeyValues:responseObject[@"result"][@"data"]];
                                NSString*name = [EnercryTool AES256Decrypt:self->model.personName key:MZAESKEY];
                                name = [name stringByReplacingOccurrencesOfString:@" " withString:@""];
                                NSString*nameText = nil;
                                if (index == 100) {
                                    nameText = [self.nameText.text stringByReplacingOccurrencesOfString:@" " withString:@""];
                                }else if (index == 101){
                                    nameText = [userModel.name stringByReplacingOccurrencesOfString:@" " withString:@""];
                                }
                                if ([name isEqualToString:nameText]) {
                                    DistrictAuthenticationInfoController *vc = [Storyboard instantiateViewControllerWithIdentifier:@"DistrictAuthenticationInfoController"];
                                    vc.title = @"补贴信息";
                                    vc.type = self.type;
                                    vc.model = self->model;
                                    [self.navigationController pushViewController:vc animated:YES];
                                }else{
                                    [SVProgressHUD showInfoWithStatus:@"请输入正确的姓名"];
                                }
                                
                              
                            }
                            
                        }else if ([code isEqualToString:@"200003"]){
                            [self alertShow:@"用户不存在"];
                        }else if ([code isEqualToString:@"200004"]){
                            [self alertShow:@"不在认证期"];
                        }else if ([code isEqualToString:@"200005"]){
                            [self alertShow:@"已认证"];
                        }else if ([code isEqualToString:@"200006"]){
                            [self alertShow:@"状态异常无法认证"];
                        }else if ([code isEqualToString:@"200007"]){
                            [self judgeAccountAuthStateRequest];
                            
                            return;
                        } else{
                            [self alertShow:desc];
                        }
                    }
                    
                    
                }else if ([state isEqualToString:@"700"]){
                    [self reloadData];
                    return;
                }else{
                    [self alertShow:describe];
                }
                   
               }else{
                   [self alertShow:@"服务器异常"];
               }
        
        [KKLoadingAnimationView dismiss];
    } Failure:^(NSError * _Nonnull error) {
        [KKLoadingAnimationView dismiss];
        NSLog(@"error:%@",error);
    }];
}

- (void)reloadData
{
    WeakSelf
//    [NetworkTokenRequest getTokenSuccess:^(BOOL success) {
//        if (success) {
//            [weakSelf queryPersonalInfoRequest:100];
//        }else{
//            [self alertShow:@"请求失败"];
//        }
//    }];
    
    NSString *urlString = [NSString stringWithFormat:@"%@%@",[NetworkConfig ipYouFuVerityConfig],GetMZTokenRequest];
    NSLog(@"优抚认证url:%@",urlString);
    NSInteger userId = [getPeopleID PeopleID];
    NSString *telephone = [getPeopleID PeopleIphoneNmber];
    NSDictionary *dicPara = @{
       @"loginId":[NSNumber numberWithInteger:userId],
       @"telephone":telephone
    };
    [KKLoadingAnimationView show];
    [NetworkRequest Get:urlString Params:dicPara Success:^(id _Nonnull responseObject) {
        if ([responseObject isKindOfClass:[NSDictionary class]]) {
            NSString *state = [NSString stringWithFormat:@"%@",responseObject[@"state"]];
            if ([state isEqualToString:@"200"]) {
                
                NSString *token = responseObject[@"result"];
                [UserDefault setObject:token forKey:@"token"];
                [weakSelf queryPersonalInfoRequest:100];
                return;
            }
        }
        [KKLoadingAnimationView dismiss];
        [SVProgressHUD showErrorWithStatus:@"请求失败"];
    } Failure:^(NSError* error) {
        [KKLoadingAnimationView dismiss];
        [SVProgressHUD showErrorWithStatus:@"网络异常"];
    }];
    
}

- (void)alertShow:(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)numberUpperLimitAlert {
    [KKAuthWhiteAlertView showAlertViewWithVC:self type:KKAuthWhiteAlertViewTypeUpper  title:@"人数已达上限" message:@"为补贴发放更安全，您今日认证人数已达上限，请明天再试" block:nil];
}

#pragma mark - 做实名认证提示
- (void)makeAccountAuthAlert {
    [KKAuthWhiteAlertView showAlertViewWithVC:self type:KKAuthWhiteAlertViewTypeAuth title:@"人数已达上限" message:@"为补贴发放更安全，同一账户认证多人需实名认证" block:^{
        [self goToAuthVC];
    }];
}


#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 ipESSCConfig],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"]) {
                
                //[self alertShow:@"该账户当天认证人数已达上限"];
                
                [self numberUpperLimitAlert];
                
            }else if ([code isEqualToString:@"204"]) {
                
                [self makeAccountAuthAlert];
                //[self goToAuthVC];
            }else {
                [self alertShow:describe];
            }
        }else{
            [self alertShow:@"服务器异常"];
        }
        
        
    } Failure:^(NSError* error) {
        [KKLoadingAnimationView dismiss];
        NSLog(@"error:%@",error);
        [self alertShow:@"网络异常"];
        
    }];
}

#pragma mark - 跳转到实名认证页面
- (void)goToAuthVC {
    NSString*nameText = [self.nameText.text stringByReplacingOccurrencesOfString:@" " withString:@""];
    NSString*idText = [self.IDText.text stringByReplacingOccurrencesOfString:@" " withString:@""];
    
    KKUserAuthViewController* vc = [KKUserAuthViewController new];
    vc.title = @"实名认证";
    vc.nameTT = nameText;
    vc.numTT = idText;
    
    if ([self.type isEqualToString:@"butie"]) {
        vc.type = KKUserAuthFromVCTypeBuTie;
    }else {
        vc.type = KKUserAuthFromVCTypeYouFu;
    }
    
    vc.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:vc animated:YES];
}


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

#pragma mark - 输入框实时变化改变按钮颜色
-(void)textFieldDidChange:(UITextField *)theTextField
{
    [self refreshBtnState];
}


#pragma mark - 刷新按钮状态
- (void)refreshBtnState
{
    if (self.nameText.text.length <= 1 || self.IDText.text.length <= 3 ||self.button_xieyi.selected == NO) {
        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 - UICollectionViewDataSource
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return 1;
}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    if (collectionView == self.collectionView) {
        return 3;
    }
    
    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{
    if (collectionView == self.collectionView) {
         RZBottomCell * cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"userCell" forIndexPath:indexPath];
         if (indexPath.item == 0){
            cell.lb_title.text = @"认证记录";
            cell.img.image = [UIImage imageNamed:@"bottom_rzHistory"];
        }else if (indexPath.item == 1){
            cell.lb_title.text = @"养老机构";
            cell.img.image = [UIImage imageNamed:@"bottom_ssjigou"];
        }else if (indexPath.item == 2){
            cell.lb_title.text = @"健康";
            cell.img.image = [UIImage imageNamed:@"life_unselect"];
        }
        return cell;
    }
    
    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{
    
    if (self.collectionView == collectionView) {
        CGFloat width =  CGRectGetWidth(collectionView.bounds)  /3 ;
         CGFloat realWidth = CGRectGetWidth(collectionView.bounds)   - floor(width)*(3 - 1);
         // CGFloat itemW = K_ScreenWidth/array.count;
         if (indexPath.item == 0) {
             return CGSizeMake(realWidth, 49);
         }

        return CGSizeMake(floor(width), 49);
    }
    
    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
{
    
    if (self.collectionView == collectionView) {
        if (indexPath.item == 2) {

            self.tabBarController.selectedIndex = 3;
            [self.navigationController popToRootViewControllerAnimated:YES];



        }else if (indexPath.item == 0){
            
            AuthenticationListViewController *vc = [[AuthenticationListViewController alloc]init];
            vc.title = @"认证记录";
            vc.hidesBottomBarWhenPushed = YES;
            vc.type = self.type;

            [self.navigationController pushViewController:vc animated:YES];
            return;
            /*
        BOOL success  = NO;
        for (UIViewController*vc in self.navigationController.viewControllers) {
            if ([vc isKindOfClass:[SSTerminationViewController class]]) {
                success = YES;
                [self.navigationController popToViewController:vc animated:YES];
                break;
            }
        }

        if (success) {
            return;
        }

        SSTerminationViewController *vc = [[SSTerminationViewController alloc]init];
        vc.title = @"电子社保卡";

        //vc.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:vc animated:YES];
             */
        }else if (indexPath.item == 1){
             NSString*city = [[NSUserDefaults standardUserDefaults]objectForKey:@"locationCity"];
               if ([NSString blankString:city]) {
                          city = @"北京市";
               }
                       
                          
           WebViewController *tc=[WebViewController new];
           
           NSString*url = [NSString stringWithFormat:@"http://nginx.weface.com.cn/appH5/government/lib/oldPeople.html?city=%@",city];
           url = [url stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
           tc.URL =[NSURL URLWithString:url];
                   tc.hidesBottomBarWhenPushed =YES;
           tc.janalytics = @"养老机构";
           [self.navigationController pushViewController:tc animated:YES];

        }else if (indexPath.item == 2){
            self.tabBarController.selectedIndex = 1;
            [self.navigationController popToRootViewControllerAnimated:YES];
        }
        
        return;
    }
    
    userModel = self.dataArray[indexPath.item];
    
    
//    if (userModel.timeStamp && [self isSameDay:[self UTCDateFromTimeStamap:userModel.timeStamp] date2:[NSDate date]]) {
//        [self alertSHOW:@"该用户当天已认证成功"];
//    }else{
//        [self queryPersonalInfoRequest:101];
//    }
    
    [self queryPersonalInfoRequest:101];
    
    
}


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


#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]) {
        [Tools showMessage:@"身份证识别错误,请重新拍摄"];
        return;
    }
    
    
    self.IDText.text =  num;
    
    [self refreshBtnState];
    
}

- (void)sendTakeImage:(TCARD_TYPE) iCardType image:(UIImage *)cardImage
{
    //self.cardImg = cardImage;
}


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

#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_rzUser2 (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_rzUser2"]){
                NSString *alertStr = [NSString stringWithFormat:@"ALTER TABLE %@ ADD %@ text",@"t_rzUser2",@"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.执行查询语句
        NSInteger userId = [UserDefault integerForKey:@"userId"];
        NSString * sql = [NSString stringWithFormat:@"SELECT * FROM t_rzUser2 where userid = '%ld'",userId];
        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 = [EnercryTool AES256Decrypt:name key:MZAESKEY];
            model.idNumber = [EnercryTool AES256Decrypt:idNumber key:MZAESKEY];
            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) {
        [self hiddenCollection:YES];
    }else{
        [self hiddenCollection:NO];
        [_mainCollectionView reloadData];
    }
    
    
}


#pragma mark - 创建补贴认证表
- (void)creatTable2
{
    //1.获得数据库文件的路径
    NSLog(@"表格路径:%@",[self getDBPath]);
     //2.获得数据库
    FMDatabase *db=[FMDatabase databaseWithPath:[self getDBPath]];
    if ([db open]) {
         //4.创表
        NSString* sql = @"CREATE TABLE IF NOT EXISTS t_rzUser3 (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_rzUser3"]){
                NSString *alertStr = [NSString stringWithFormat:@"ALTER TABLE %@ ADD %@ text",@"t_rzUser3",@"timeSp"];
                BOOL worked = [db executeUpdate:alertStr];
                if(worked){
                    NSLog(@"插入成功");
                }else{
                    NSLog(@"插入失败");
                }
            }
            
        }else{
            NSLog(@"创表失败");
        }
        
        [db close];
    }
    
    [self queryData2];
    
    
}

- (void)queryData2
{
    
    //1.获得数据库文件的路径
   NSLog(@"表格路径:%@",[self getDBPath]);
    NSMutableArray * array = [NSMutableArray array];
    //2.获得数据库
   FMDatabase *db=[FMDatabase databaseWithPath:[self getDBPath]];
    
    if ([db open]) {
        // 1.执行查询语句
        NSInteger userId = [UserDefault integerForKey:@"userId"];
        NSString * sql = [NSString stringWithFormat:@"SELECT * FROM t_rzUser3 where userid = '%ld'",userId];
        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 = [EnercryTool AES256Decrypt:name key:MZAESKEY];
            model.idNumber = [EnercryTool AES256Decrypt:idNumber key:MZAESKEY];
            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) {
        [self hiddenCollection:YES];
    }else{
        [self hiddenCollection:NO];
        [_mainCollectionView reloadData];
    }
    
    
}


- (NSString *)getDBPath
{
     NSString *doc= [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
        return [doc stringByAppendingPathComponent:@"rzUserlist.sqlite"];

}

#pragma mark - 隐藏或显示collectionview
- (void)hiddenCollection:(BOOL)hidden
{
   
    _mainCollectionView.hidden = hidden;
    _lb_message.hidden = hidden;
    _rightLine.hidden = hidden;
    _leftLine.hidden = hidden;
//    self.whiteView.hidden = !hidden;
//    self.topCircleImg.hidden = !hidden;
    
    if (hidden) {
        CGRect nameImgFrame = self.nameImg.frame;
        CGFloat nameImgMinY =  22 * WIDTHRADIU;
        nameImgFrame.origin.y = nameImgMinY;
        self.nameImg.frame = nameImgFrame;
        
        CGRect topBackImgFrame = self.backImgView.frame;
        topBackImgFrame.size.height = 345 * WIDTHRADIU;
        self.backImgView.frame = topBackImgFrame;
        self.topBg.image = [UIImage imageNamed:@"社保认证弧度"];
        
    }else{
        CGRect nameImgFrame = self.nameImg.frame;
        CGFloat nameImgMinY =  22 * WIDTHRADIU;
        nameImgFrame.origin.y = nameImgMinY;
        self.nameImg.frame = nameImgFrame;
        
        CGRect topBackImgFrame = self.backImgView.frame;
        topBackImgFrame.size.height = 275 * WIDTHRADIU;
        self.backImgView.frame = topBackImgFrame;
        
        self.topBg.image = [UIImage imageNamed:@"社保认证弧度_s"];
        
        self.videoImage.hidden = YES;
        self.clearView.hidden = YES;
        
        [self.agressBtn mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(self->_mainCollectionView.mas_bottom).offset(17 * WIDTHRADIU);
            make.left.offset(27 * WIDTHRADIU);
            make.width.height.offset(15);
        }];
        
        
        [self.cardImage mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.left.offset(65 * WIDTHRADIU);
            make.top.equalTo(self.IDText.mas_bottom).offset(24 * WIDTHRADIU);
            make.width.offset(114 * WIDTHRADIU);
            make.height.offset(71 * WIDTHRADIU);
        }];
        
        [self.cardBtn mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(self.cardImage.mas_right).offset(53 * WIDTHRADIU);
            make.centerY.equalTo(self.cardImage);
            make.width.offset(114 * WIDTHRADIU);
            make.height.offset(40 * WIDTHRADIU);
        }];
    }
    
//    CGFloat y = hidden ? CGRectGetMaxY(self.backImgView.frame) + 10 * WIDTHRADIU :CGRectGetMaxY(self.backImgView.frame) + 58 * WIDTHRADIU + 62;
//    CGRect frame = self.agressBtn.frame;
//    frame.origin.y = y;
//    self.agressBtn.frame = frame;
//    self.scrollView.contentSize = CGSizeMake(ScreenWidth,self.agressBtn.maxY + 83 + 45 * WIDTHRADIU);
    
        
}

#pragma mark - 启动ocr
- (void)startOCR
{
    
    #if TARGET_IPHONE_SIMULATOR == 0
    SCCaptureCameraController*con = [[SCCaptureCameraController alloc] init];
    con.scNaigationDelegate = self;
    con.iCardType = TIDCARD2; // 其他证件以此类推
    con.isDisPlayTxt = NO;
    con.ScanMode = TIDC_SCAN_MODE;
    con.modalPresentationStyle = UIModalPresentationFullScreen;
    [self presentViewController:con animated:YES completion:NULL];
    #endif
    
}


#pragma mark - event response
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    [self.view endEditing:YES];
}
- (void)tapEmptyViewClick:(UITapGestureRecognizer *)tap
{
    [self.view endEditing:YES];
}

- (IBAction)scanClick:(UIButton *)sender {
    
    [self startOCR];
    
}


- (IBAction)goToNextVC:(UIButton *)sender {
    
    
    [self.view endEditing:YES];
    if (self.tf_name.text.length == 0 || self.tf_IdCard.text.length == 0) {
        [SVProgressHUD showErrorWithStatus:@"姓名和身份证号不能为空"];
        return;
    }
    
    if (![IDCardNumber_Validate isValidateIDCardString:self.tf_IdCard.text]) {
        [SVProgressHUD showErrorWithStatus:@"身份证号格式不正确"];
        return;
    }
    
    [self queryPersonalInfoRequest:100];
    
}

- (void)explainIdentifly:(UIButton *)sender
{
    [self startOCR];
}

- (void)KankanXieYi:(UIButton *)sender
{
    
    UIStoryboard *sb  =[UIStoryboard storyboardWithName:@"Main" bundle:nil];
    kankanshebaoxieyi *kankan = [sb instantiateViewControllerWithIdentifier:@"kankanshebaoxieyi"];
    kankan.title = @"用户服务协议";
    kankan.hidesBottomBarWhenPushed =YES;
    [self.navigationController pushViewController:kankan animated:YES];
    
//    WebVC*vc = [[WebVC alloc]init];
//    vc.title = @"用户服务协议";
//    vc.url = @"http://nginx.weface.com.cn/agreement/useragree.html";
//    [self.navigationController pushViewController:vc animated:YES];
}

- (void)ssssselfe:(UIButton *)sender
{
    self.button_xieyi.selected = !self.button_xieyi.selected;
    [self refreshBtnState];
}
#pragma mark - 下一步
- (void)photo:(UIButton *)sender
{
    [self.view endEditing:YES];
    if (self.nameText.text.length == 0 || self.IDText.text.length == 0) {
        [SVProgressHUD showErrorWithStatus:@"姓名和身份证号不能为空"];
        return;
    }
    
    if (![IDCardNumber_Validate isValidateIDCardString:self.IDText.text]) {
        [SVProgressHUD showErrorWithStatus:@"身份证号格式不正确"];
        return;
    }
    
    timeForButtonCount *times=[[timeForButtonCount alloc]initMustTakeReturn:nil];
    [times methodWithTimeCount:sender];
    
    [self queryPersonalInfoRequest:100];
    
    
}

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

- (void)backClick
{
    [self.navigationController popViewControllerAnimated:YES];
}
#pragma mark - private methods
// 判断是否是同一天
- (BOOL)isSameDay:(NSDate*)date1 date2:(NSDate*)date2
{
    NSCalendar* calendar = [NSCalendar currentCalendar];
    unsigned unitFlags = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit;
    NSDateComponents* comp1 = [calendar components:unitFlags fromDate:date1];
    NSDateComponents* comp2 = [calendar components:unitFlags fromDate:date2];
    return [comp1 day] == [comp2 day] &&
    [comp1 month] == [comp2 month] &&
    [comp1 year] == [comp2 year];
}
//时间戳转UTCDate
-(NSDate *)UTCDateFromTimeStamap:(NSString *)timeStamap
{
    NSTimeInterval timeInterval=[timeStamap doubleValue]/1000;
    //  /1000;传入的时间戳timeStamap如果是精确到毫秒的记得要/1000
    NSDate *UTCDate=[NSDate dateWithTimeIntervalSince1970:timeInterval];
    return UTCDate;
}

#pragma mark - getters and setters
- (UIScrollView *)scrollView
{
    if (!_scrollView) {
        _scrollView = [[UIScrollView alloc]initWithFrame:CGRectMake(0,cl_kNavigationBarHeight, ScreenWidth, ScreenHeight- cl_kNavigationBarHeight  - 49)];
        _scrollView.contentSize = CGSizeMake(ScreenWidth, 0);
        _scrollView.showsHorizontalScrollIndicator = NO;
        _scrollView.showsVerticalScrollIndicator = NO;
        _scrollView.delegate = self;
         _scrollView.contentOffset = CGPointMake(0,0);
        _scrollView.backgroundColor = [UIColor whiteColor];
        

        
        UITapGestureRecognizer*tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapEmptyViewClick:)];

       // [_scrollView addGestureRecognizer:tap];
        
        //背景图片
        UIView* topBackImg = [[UIView alloc]initWithFrame:CGRectMake(0, 0 *ScreenWidth, ScreenWidth, 345 * WIDTHRADIU)];
        topBackImg.backgroundColor = [UIColor whiteColor];
        self.backImgView = topBackImg;
        [topBackImg addGestureRecognizer:tap];
        [_scrollView addSubview:topBackImg];
        
        UIImageView* bgImg = [UIImageView new];
        bgImg.image = [UIImage imageNamed:@"社保认证弧度"];
        [topBackImg addSubview:bgImg];
        self.topBg = bgImg;
        [bgImg mas_makeConstraints:^(MASConstraintMaker *make) {
            make.edges.offset(0);
        }];
        
        
        /*
        //顶部圆弧
        UIImageView* topCircleImg = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, 55 * WIDTHRADIU)];
        topCircleImg.image = [UIImage imageNamed:@"社保认证弧度"];
        [topBackImg addSubview:topCircleImg];
         self.topCircleImg = topCircleImg;
         
        //白色悬浮块
         UIView* whiteView = [[UIView alloc]initWithFrame:CGRectMake((ScreenWidth - 340 * WIDTHRADIU)/2, 0, 340 * WIDTHRADIU, 71 * WIDTHRADIU)];
         whiteView.backgroundColor = [UIColor whiteColor];
         whiteView.layer.cornerRadius = 10 * WIDTHRADIU;
         whiteView.layer.shadowColor = [UIColor colorWithHex:0xe4eef6].CGColor;
         whiteView.layer.shadowOpacity = 0.8;
         whiteView.layer.shadowRadius = 2 * WIDTHRADIU;
         whiteView.layer.shadowOffset = CGSizeMake(0, 0);
         [topBackImg addSubview:whiteView];
         self.whiteView = whiteView;
        
        //流程进度条
        UIView*progressLine = [[UIView alloc]initWithFrame:CGRectMake(43 * WIDTHRADIU, 25 * WIDTHRADIU, 244 * WIDTHRADIU, 4 * WIDTHRADIU)];
        progressLine.backgroundColor = [UIColor colorWithHex:0xfdc1a0];
        [whiteView addSubview:progressLine];
        NSArray*progressArray = @[@"拍身份证",@"信息核对",@"人脸识别"];
        for (int i = 0; i < 3; i++) {
            UIImageView*imageView = [[UIImageView alloc]init];
            imageView.image = [UIImage imageNamed:[NSString stringWithFormat:@"rz_0%d",i+1]];
            imageView.frame = CGRectMake(31* WIDTHRADIU + (34 * WIDTHRADIU + 88*WIDTHRADIU)*i, 10 * WIDTHRADIU, 34 * WIDTHRADIU, 34* WIDTHRADIU);
            [whiteView addSubview:imageView];
            UILabel*lb = [[UILabel alloc]init];
            lb.textColor = [UIColor colorWithHex:0x808080];
            lb.font = [UIFont systemFontOfSize:14 * WIDTHRADIU];
            lb.textAlignment = NSTextAlignmentCenter;
            lb.text = progressArray[i];
            [whiteView addSubview:lb];
            [lb mas_makeConstraints:^(MASConstraintMaker *make) {
                make.top.equalTo(imageView.mas_bottom).offset(2 * WIDTHRADIU);
                make.centerX.equalTo(imageView);
            }];
            
        }
         
         */
        
        //姓名
        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;
        tf_name.returnKeyType = UIReturnKeyDone;
        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);
        }];
        
        UITextField*tf_id = [[UITextField alloc]init];
        tf_id.textColor = [UIColor colorWithHex:0x4d4d4d];
        tf_id.font = [UIFont systemFontOfSize:15 * WIDTHRADIU];
        tf_id.placeholder = @"请输入身份证信息";
        tf_id.delegate = self;
        tf_id.returnKeyType = UIReturnKeyDone;
        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);
        }];
        
        
        [tf_name addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];

        [tf_id addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
        
        
        
        
       
        
//        CGFloat wordWidth = 25;
//        CGFloat leftPadding = 28 * WIDTHRADIU;
        CGFloat cardWidth = 114 * WIDTHRADIU;
        CGFloat buttonWidth = 114 * WIDTHRADIU;
        
        //视频图片
        UIImageView*videoView = [[UIImageView alloc]init];
        videoView.image = [UIImage imageNamed:@"authVideo"];
        [topBackImg addSubview:videoView];
        
        videoView.userInteractionEnabled = YES;
        
        UITapGestureRecognizer* tap2 = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(watchClick:)];
        
        [videoView addGestureRecognizer:tap2];
        
        self.videoImage = videoView;
        
        [videoView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.offset(65 * WIDTHRADIU);
            make.top.equalTo(tf_id.mas_bottom).offset(24 * WIDTHRADIU);
            make.width.offset(cardWidth);
            make.height.offset(62.5 * WIDTHRADIU);
        }];
        
        UIView* clearView = [UIView new];
        [topBackImg addSubview:clearView];
        self.clearView = clearView;
        [clearView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.offset(65 * WIDTHRADIU);
            make.top.equalTo(videoView.mas_bottom);
            make.width.offset(cardWidth);
            make.height.offset(17 * WIDTHRADIU);
        }];
        
        //身份证图片
        UIImageView*IdCardView = [[UIImageView alloc]init];
        IdCardView.image = [UIImage imageNamed:@"身份证图"];
        [topBackImg addSubview:IdCardView];
        
        self.cardImage = IdCardView;
        
        
        [IdCardView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.offset(65 * WIDTHRADIU);
            make.top.equalTo(clearView.mas_bottom);
            make.width.offset(cardWidth);
            make.height.offset(71 * WIDTHRADIU);
        }];
        
        //例
//        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];
        self.cardBtn = btn;
        
        [btn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(IdCardView.mas_right).offset(25);
            make.centerY.equalTo(clearView);
            make.width.offset(buttonWidth);
            make.height.offset(40 * WIDTHRADIU);
        }];
        
        //分割线
       UILabel*lb_message = [[UILabel alloc]init];
       lb_message.text = @"选择姓名，快速认证";
       lb_message.textAlignment = NSTextAlignmentCenter;
       lb_message.textColor = [UIColor colorWithHex:0x808080];
       lb_message.font = [UIFont systemFontOfSize:15 * WIDTHRADIU];
        lb_message.hidden = YES;
       [_scrollView addSubview:lb_message];
       [lb_message setContentCompressionResistancePriority:UILayoutPriorityRequired forAxis:UILayoutConstraintAxisHorizontal];
       [lb_message setContentHuggingPriority:UILayoutPriorityRequired forAxis:UILayoutConstraintAxisHorizontal];
       [lb_message setContentHuggingPriority:UILayoutPriorityRequired forAxis:UILayoutConstraintAxisVertical];

       [lb_message mas_makeConstraints:^(MASConstraintMaker *make) {
           make.centerX.equalTo(self->_scrollView);
           make.top.equalTo(topBackImg.mas_bottom).offset(23 * WIDTHRADIU);
       }];
           
           
        //左边分割线
       UIView* leftLine = [[UIView alloc]init];
       leftLine.backgroundColor = [UIColor colorWithHex:0xcccccc];
        leftLine.hidden = YES;
       [_scrollView addSubview:leftLine];
       [leftLine mas_makeConstraints:^(MASConstraintMaker *make) {
           make.centerY.equalTo(lb_message);
           make.left.offset(18 * WIDTHRADIU);
           make.right.equalTo(lb_message.mas_left).offset(- 8 * WIDTHRADIU);
           make.height.offset(0.5);
       }];
           
        
        //右边分割线
       UIView* rightLine = [[UIView alloc]init];
       rightLine.backgroundColor = [UIColor colorWithHex:0xcccccc];
        rightLine.hidden = YES;
       [_scrollView addSubview:rightLine];
       
       [rightLine mas_makeConstraints:^(MASConstraintMaker *make) {
           make.centerY.equalTo(lb_message.mas_centerY);
           make.left.equalTo(lb_message.mas_right).offset(8 * WIDTHRADIU);
           make.right.equalTo(self->_scrollView.mas_right).offset(-18 * WIDTHRADIU);
           make.width.equalTo(leftLine);
           make.height.offset(0.5);
       }];
        
     _lb_message = lb_message;
     _leftLine = leftLine;
     _rightLine = rightLine;
     
     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"];
     collectionView.hidden = YES;
     [_scrollView addSubview:collectionView];
     _mainCollectionView = collectionView;
     
     [_mainCollectionView mas_makeConstraints:^(MASConstraintMaker *make) {
         make.top.equalTo(lb_message.mas_bottom).offset(8 * WIDTHRADIU);
         make.left.right.offset(0);
         make.height.offset(62);
     }];
        
    UIButton* agressBtn = [UIButton buttonWithType:UIButtonTypeCustom];
     [agressBtn setImage:[UIImage imageNamed:@"check_unselected"] forState:UIControlStateNormal];
     [agressBtn setImage:[UIImage imageNamed:@"check_selected"] forState:UIControlStateSelected];
     self.button_xieyi = agressBtn;
     self.button_xieyi.selected = YES;
     [agressBtn addTarget:self action:@selector(ssssselfe:) forControlEvents:UIControlEventTouchUpInside];
     [_scrollView addSubview:agressBtn];
     
     agressBtn.frame = CGRectMake(27 * WIDTHRADIU, CGRectGetMaxY(topBackImg.frame) + 10* WIDTHRADIU, 30, 30);
     self.agressBtn = agressBtn;
     
     //协议button
     UIButton* xieyiBtn = [UIButton buttonWithType:UIButtonTypeCustom];
     [xieyiBtn setTitle:@"同意  <<用户服务协议>>" forState:UIControlStateNormal];
     [xieyiBtn setTitleColor:[UIColor colorWithHex:0x333333] forState:UIControlStateNormal];
     xieyiBtn.titleLabel.font = [UIFont systemFontOfSize:10];
     [xieyiBtn addTarget:self action:@selector(KankanXieYi:) forControlEvents:UIControlEventTouchUpInside];
     [_scrollView addSubview:xieyiBtn];
     
     [xieyiBtn mas_makeConstraints:^(MASConstraintMaker *make) {
         make.centerY.equalTo(agressBtn);
         make.left.equalTo(agressBtn.mas_right).offset(0);
         make.width.offset(120);
         make.height.offset(25);
     }];
        
        

        //hiddenView
        UIView* hiddenView = [[UIView alloc]init];
        hiddenView.backgroundColor = [UIColor clearColor];
        //hiddenView.hidden = YES;
        self.hideView = hiddenView;
        [_scrollView addSubview:hiddenView];
        
        [hiddenView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(agressBtn.mas_bottom).offset(10 * WIDTHRADIU);
            make.left.offset(22 * WIDTHRADIU);
            make.right.offset(-33 * WIDTHRADIU);
            make.height.offset(24 * WIDTHRADIU);
        }];
        
        //提示message
        
        NSString*message = @"提示：该认证仅支持军人补贴认证";
        if ([self.type isEqualToString:@"butie"]) {
            message = @"仅支持民政、卫健和退役军人的各种补贴";
        }
        
        UILabel* lb_tip = [UILabel new];
        lb_tip.text = message;
        lb_tip.textColor = [UIColor colorWithHex:0x808080];
        lb_tip.font = [UIFont fontWithName:@"PingFang SC" size:14* WIDTHRADIU];
        [hiddenView addSubview:lb_tip];
        
//        UIButton* messageBtn = [UIButton buttonWithType:UIButtonTypeCustom];
//        [messageBtn setTitle:message forState:UIControlStateNormal];
//        [messageBtn setTitleColor:[UIColor colorWithHex:0xE94036] forState:UIControlStateNormal];
//        messageBtn.titleLabel.font = [UIFont fontWithName:@"PingFang SC" size:14* WIDTHRADIU];
//        [messageBtn setImage:[UIImage imageNamed:@"椭圆-12"] forState:UIControlStateNormal];
        [hiddenView addSubview:lb_tip];
        [lb_tip mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.left.bottom.right.offset(0);
        }];
       // self.messageBtn = messageBtn;
     
     
     
     //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(hiddenView.mas_bottom).offset(10);
         make.left.offset(27 * WIDTHRADIU);
         make.right.offset(-27 * WIDTHRADIU);
         make.height .offset(45 * WIDTHRADIU);
     }];
    
    UILabel*lb_shengming = [[UILabel alloc]init];
     lb_shengming.text = @"在此声明,此app内发生的所有事件与Apple Inc. 无关";
     lb_shengming.textColor = [UIColor colorWithHex:0x828282];
     lb_shengming.font = [UIFont systemFontOfSize:13];
     lb_shengming.textAlignment = NSTextAlignmentCenter;
     [_scrollView addSubview:lb_shengming];
     [lb_shengming mas_makeConstraints:^(MASConstraintMaker *make) {
         make.top.equalTo(nextBtn.mas_bottom).offset(20);
         make.centerX.offset(0);
         make.height.mas_greaterThanOrEqualTo(10);
         make.bottom.mas_equalTo( - 10 );
     }];
     
     
     
    }
    return _scrollView;
}

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

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