//
//  PhotoViewController.m
//  Open
//
//  Created by 黄江涛 on 16/9/7.
//  Copyright © 2016年 黄江涛 . All rights reserved.
//

//这里修改了cJIAJIA
@import AVKit;
#import "PhotoViewController.h"

//#import <AVFoundation/AVFoundation.h>
#import <MediaPlayer/MediaPlayer.h>
//#import <AVFoundation/AVTime.h>
//#import <AVFoundation/AVAsset.h>
//#import <AVFoundation/AVAssetImageGenerator.h>
//#import <AFNetworking.h>
//#import "SVProgressHUD.h"
#import "FFNetworkUpload.h"
#import <AVFoundation/AVFoundation.h>
#import <MediaPlayer/MediaPlayer.h>
#import "AFNetworking.h"
#import "SecurityUtil.h"
#import "GTMBase64.h"
#import "MyMD5.h"
#import "pickerViewController.h"
#import "CityNetManager.h"
#import "SCCaptureCameraController.h"
#import "IOSOCRAPI.h"
#import "Globaltypedef.h"
#import "successViewController.h"
#import "kankanshebaoxieyi.h"

//雷俊博
#import "Constants.h"
#import "SocialSecurityApproveSuccessVC.h"
#import "CQColorfulAlertView.h"

#import <Contacts/Contacts.h>

//雷俊博自定义参保信息vc
#import "InsuredInfoViewController.h"
#import "quickInsuredInfoViewController.h"
#import "RZUserCollectionViewCell.h"
#import "rzUserModel.h"
#import "EmergencyContactPeople.h"


//static AFHTTPSessionManager *manager = nil;
@interface PhotoViewController ()<UIImagePickerControllerDelegate,UINavigationControllerDelegate,UITextFieldDelegate,UINavigationControllerDelegate,UIImagePickerControllerDelegate,SCNavigationControllerDelegate,UICollectionViewDelegate,UICollectionViewDataSource>
{
  int   numberCounts;
    NSString *ggtime;
    NSString *ggaddress;
    NSString *ggimage;
    BOOL contactAllow;
    rzUserModel* userModel;
    
    
    //记录是普通认证还是快速认证
    NSInteger currentIndex;
    NSString* name;
    NSString* idNumber;
    NSString* bak;
    NSString*province;
    NSString* city;
    NSString* county;
    
    
}




@property(nonatomic,strong)	 AFHTTPSessionManager *manager;
@property(nonatomic,strong)	 UIImagePickerController *_imagePickerController;
@property(nonatomic)BOOL isEnter;

@property(nonatomic,strong)NSMutableArray* imageArray;
@property(nonatomic,strong)	UIImagePickerController *imagPicker;


@property (weak, nonatomic) IBOutlet UIButton *PhotoBtn;
@property (weak, nonatomic) IBOutlet UIButton *searchButton2;
@property(nonatomic,strong)NSString* IP;
@property(nonatomic,strong)FFNetworkUpload* upload;

@property(nonatomic,strong)	 NSMutableArray *array;
@property(nonatomic,strong)	 NSMutableArray *baochunShuZu;
@property(nonatomic,strong)	 NSMutableArray *dataArr;
@property(nonatomic,strong)	 UILabel *label;

@property (weak, nonatomic) IBOutlet UIImageView *backgurardView;

@property (weak, nonatomic) IBOutlet UIView *hideView;

@property (weak, nonatomic) IBOutlet UIImageView *ocrPhoto;
@property(nonatomic,strong)NSString  *ocrBase64;
@property(nonatomic,strong)NSString *ocrBase64_;

@property (weak, nonatomic) IBOutlet UIButton *button_xieyi;


//显示最新认证对象

@property (weak, nonatomic) IBOutlet NSLayoutConstraint *topConstant;

@property (nonatomic, strong)UIView *topView;

@property (nonatomic, strong)UIImageView *img_loudspeaker;

@property (nonatomic, strong)UILabel *lb_left;

@property (nonatomic, strong)UIButton *btn_right;


@property(nonatomic,strong)FMDatabase *db;

@property (weak, nonatomic) IBOutlet UICollectionView *collectionView;
@property (weak, nonatomic) IBOutlet UILabel *lb_middleMessage;
@property (weak, nonatomic) IBOutlet UIView *leftLine;
@property (weak, nonatomic) IBOutlet UIView *rightLine;



@property (nonatomic, strong)NSMutableArray* dataArray;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *lb_middleMessageTopLayoutConstraint;
@property (weak, nonatomic) IBOutlet UIButton *btn_getIdInfo;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *backImgTopLayoutConstraint;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *photoBtnTopLayoutConstraint;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *photoBtnAndImgTopLayoutConstraint;





@end

@implementation PhotoViewController
-(NSMutableArray *)array
{
    if (!_array) {
        _array =[NSMutableArray new];
      
    }
    return _array;
    
}
-(NSMutableArray *)baochunShuZu
{

    if (!_baochunShuZu) {
        _baochunShuZu =[NSMutableArray new];
      
    }
    return _baochunShuZu;


}
-(NSMutableArray *)dataArr
{
    if (!_dataArr) {
        _dataArr =[NSMutableArray new];
    }
    return _dataArr;
}



-(void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    [JANALYTICSService startLogPageView:@"社保认证 - 基础信息验证"];
     [MobClick beginLogPageView:@"社保认证 - 基础信息验证"];
}
-(void)viewDidDisappear:(BOOL)animated{
    [super viewDidDisappear:animated];
    [JANALYTICSService stopLogPageView:@"社保认证 - 基础信息验证"];
    [MobClick endLogPageView:@"社保认证 - 基础信息验证"];

}
-(void)getDataCompleteHandle:(NSInteger)index
{
    //url
    NSString *path =@"";
    NSString *NameEnerypt= @"";
    NSString *IdentiftyEnerypt = @"";
    path  = [IPDIZHI stringByAppendingString:@"/socialsecurity/kankan/province"];
    NSLog(@"%@",path);
    
    
    
    currentIndex = index;
   
    //对输入框的身份证去空格
  NSString *newStr = [self.IDText.text  stringByReplacingOccurrencesOfString:@" " withString:@""];

    NSLog(@"%@",newStr);
    
    if (index == 100) {
        name = self.nameText.text;
        idNumber = self.IDText.text;
        //姓名AES加密
        NameEnerypt =  [EnercryTool A:self.nameText.text];
        //身份证号AES加密
        IdentiftyEnerypt = [EnercryTool A:newStr];
        NSUserDefaults* userDefault=[NSUserDefaults standardUserDefaults];
        [userDefault setValue:self.nameText.text forKey:@"name"];
        [userDefault setValue:newStr  forKey:@"identityNumber"];
        [userDefault synchronize];
        BOOL IDCardInjudicious = [IDCardNumber_Validate isValidateIDCardString:newStr];
           if (IDCardInjudicious) {
          
           }else
           {
         [SVProgressHUD showErrorWithStatus:@"身份证上有格式上的错误"];
               self.hideView.hidden =NO;
                  self.backgurardView.image =[UIImage imageNamed:@"textFieldBackGuardRed"];
               return;
           }
    }else{
        name = userModel.name;
        idNumber = userModel.idNumber;
       //姓名AES加密
        NameEnerypt =  [EnercryTool A:userModel.name];
        //身份证号AES加密
        IdentiftyEnerypt = [EnercryTool A:userModel.idNumber];
        NSUserDefaults* userDefault=[NSUserDefaults standardUserDefaults];
        [userDefault setValue:userModel.name forKey:@"name"];
        [userDefault setValue:userModel.idNumber  forKey:@"identityNumber"];
        [userDefault synchronize];
    }
    
    [SVProgressHUD shows];
    [CityNetManager getMoreCityForThisMethod:@"name" encrypt:NameEnerypt andTheOther:@"identityNumber" twoEncrypt:IdentiftyEnerypt  andPutThePathForThis:path andID:[getPeopleID PeopleID] completionHandle:^(CityModel *model, NSError *error) {
       
        if(error){
            [SVProgressHUD doneShow];
            [SVProgressHUD showErrorWithStatus:@"服务器无法连接"];
            return;
        }
        
        AppDelegate *delegate=(AppDelegate*)[[UIApplication sharedApplication]delegate];
         paramResult *model_2 =  (paramResult*)model.param;
        self.cityModel = [[CityModel alloc]init];
        self->ggimage =   MHSafeStrings(model_2.verifyPhoto);
        self->ggtime = MHSafeStrings(model_2.vafiryTime);
        self->ggaddress =MHSafeStrings(model_2.verifyAdress);
        self.cityModel.param =model_2;
        if ([[EnercryTool decryptUseDES:model_2.telphoneValue key:DESKEY] isEqualToString:@"null"] ) {
            delegate.isTel = NO;
        }else{
            delegate.telStr = [EnercryTool decryptUseDES:model_2.telphoneValue key:DESKEY];
            delegate.isTel = YES;
        }
        if (model.bak ==nil || [model.bak isEqualToString:@"pQBOvaCaU+k="]) {
            model.bak =nil;
        }
        if(model.code == 0){
             [SVProgressHUD doneShow];
            [SVProgressHUD dismiss];
            
            //雷俊博
//            SocialSecurityApproveSuccessVC *vc = [[SocialSecurityApproveSuccessVC alloc]init];
//            vc.title = @"认证成功";
//
//            vc.model = model.param;
//
//            [self.navigationController pushViewController:vc animated:YES];
            
            self->bak = model.bak;
            self->province = model_2.provinceName;
            self->city = model_2.cityName;
            self->county = model_2.countryName;
            
            [self performSegueWithIdentifier:@"successSegueTwo" sender:self];
            return;
            
        }
        
        dispatch_async(dispatch_get_main_queue(), ^{
            NSUserDefaults *userDefaults =[NSUserDefaults standardUserDefaults];
            [userDefaults setObject:model.bak forKey:@"bak"];
            [userDefaults synchronize];
            
            if (model.code == 2 ) {
                [SVProgressHUD doneShow];
                [SVProgressHUD dismiss];
                NSString *aesParam =   [[NSUserDefaults standardUserDefaults]objectForKey:@"AESparam"];
                if ([getPeopleID getpeopleLimited] == YES) {
                    
                    
                    if ([aesParam isEqualToString:@""] || aesParam == NULL ) {
                        return   [self alertSHOW:@"是否新增用户"];
                    }else{
                        [self qitalaojiLAOZUO:model andName:aesParam];
                        return;
                    }
                    
                }else{
                    if ([aesParam isEqualToString:@""] || aesParam == NULL ) {
                        return   [SVProgressHUD showErrorWithStatus:@"您不在本次认证范围内，请咨询当地社保局"];
                    }else{
                        return    [SVProgressHUD showErrorWithStatus:@"请判断姓名是否正确"];
                    }
                    
                }
            }else if(model.code == 1015){
                [SVProgressHUD doneShow];
                [SVProgressHUD dismiss];
                [self alertSHOW:@"信息未采集,请采集"];
                return;
                
            }else if(model.code == 23){
                [SVProgressHUD doneShow];
                [SVProgressHUD dismiss];
                return [SVProgressHUD showInfoWithStatus:@"不在认证时间内"];                
            }else if(model.code == 43){
                [SVProgressHUD doneShow];
                [SVProgressHUD dismiss];
                return [SVProgressHUD showInfoWithStatus:@"当前账号当天认证次数已达上限"];
                
            }else if(model.code == 24){
                [SVProgressHUD doneShow];
                [SVProgressHUD dismiss];
                
                codeSelected *code = [codeSelected MustTakeReturn:model.code];
                [code returnCodeMethod];
                
                self.nameText.userInteractionEnabled = YES;
                return ;
                
            }else if (model.code == 29){
                [SVProgressHUD doneShow];
                [SVProgressHUD dismiss];
                [CQColorfulAlertView showAuthenticationFailedAlertWithMessage:@"未采集成功,\n是否重新采集?" checkCouponButtonClickedBlock:^{
                       UIStoryboard *sb = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
                                 socialOnceViewController *once  = [sb instantiateViewControllerWithIdentifier:@"socialOnceViewController"];
                                 //            socialSecurityViewController *once = [socialSecurityViewController sharedInstance];
                              once.personPrivate = [getPeopleID getpeopleLimited] ? 1 : 0;
                                 once.offLineGather =@"";
                                 [self.navigationController pushViewController:once animated:YES];
                   }];
                return;
            }
            else if (model.code == 28 ){
                [SVProgressHUD doneShow];
                [SVProgressHUD dismiss];
                codeSelected *code = [codeSelected MustTakeReturn:model.code];
                [code returnCodeMethod];
                return;
            }
          

            [self.array addObjectsFromArray:model.result];
            if (self.array.count <= 0 ) {
                [SVProgressHUD doneShow];
                [SVProgressHUD dismiss];
                codeSelected *code = [codeSelected MustTakeReturn:model.code];
                [code returnCodeMethod];
                return ;
            }
            for (int row = 0 ; row < 31 ; row++) {
                if (self.array == nil) {
                    [SVProgressHUD doneShow];
                    [SVProgressHUD dismiss];
                    return;
                }
                CityResultModel *city =self.array[row];
                [self.baochunShuZu addObject:city.provice_name];
                NSData *data =[NSKeyedArchiver archivedDataWithRootObject:city.provice_id];
                [self.dataArr addObject:data];
            }
            //        NSUserDefaults *userDefaults =[NSUserDefaults standardUserDefaults];
            [userDefaults setObject:self.dataArr forKey:@"myPrivinceModel"];
            [userDefaults synchronize];
            
            //1.在时间段范围内可进行下一步
            //3.社保信息验证未通过
            //26.当前时间段内认证的成功次数不够
            if (model.code == 3 || model.code == 1 || model.code == 26) {
                //      [self performSegueWithIdentifier:@"GCDSegue" sender:self];
//                [SVProgressHUD doneShow];
//                [SVProgressHUD dismiss];
                
                pickerViewController *blueVC =[pickerViewController sharedInstance];
                blueVC.OCRData =self.ocrBase64;
                blueVC.OCRData_ =self.ocrBase64_;
                for (int i = 0; i < 31; i++) {
                    blueVC.array2[i] =self.baochunShuZu[i];
                }
                AppDelegate *delegate=(AppDelegate*)[[UIApplication sharedApplication]delegate];
                
                if ([[EnercryTool decryptUseDES:model_2.telphoneValue key:DESKEY] isEqualToString:@"null"] ) {
                    delegate.isTel = NO;
                }else{
                    delegate.telStr =@"";
                    if (model_2.telphoneValue == nil || [model_2.telphoneValue isEqualToString:@"null"] || [model_2.telphoneValue isEqualToString:@""] ) {
                        delegate.telStr =@"18888888888";
                    }else{
                        
                        delegate.telStr = [EnercryTool decryptUseDES:model_2.telphoneValue key:DESKEY];
                    }
                    delegate.isTel = YES;
                }
                blueVC.telStr = delegate.telStr;
                
                [self SenderTWO:model_2 index:index];
                
            }else{
                [SVProgressHUD doneShow];
                [SVProgressHUD dismiss];
                codeSelected *code = [codeSelected MustTakeReturn:model.code];
                [code returnCodeMethod];
                
            }
        });
    }];
}












-(void)SenderTWO:(paramResult*)model_2 index:(NSInteger)index{
    NSUserDefaults* userDefault=[NSUserDefaults standardUserDefaults];
    NSString *names =[userDefault objectForKey:@"name"];
    NSString *identifity =[userDefault objectForKey:@"identityNumber"];
    NSString *u =[userDefault objectForKey:@"bak"];
    NSLog(@"%@,%@",names,identifity);
    if ([u isEqualToString:@""]) {
        u =nil;
    }
    NSString *path =@"";
    path  = [IPDIZHI stringByAppendingString:@"/socialsecurity/kankan/verifyAddress"];

    NSString *telPhone =@"";
    AppDelegate *delegate=(AppDelegate*)[[UIApplication sharedApplication]delegate];
    if (delegate.isTel == YES) {
        if (delegate.telStr) {
             telPhone =delegate.telStr;
        }


        delegate.isTel =NO;
    }
    [[NSUserDefaults standardUserDefaults]setObject:MHSafeStrings(model_2.provinceName) forKey:@"provinceAABBCC"];
    
    self.paramSModel = [paramResult new];
 
    self.paramSModel =model_2;
      __weak typeof(self) wself = self;

    [CityNetManager getVeriftAdressNameToThePath:path FortheName:names encrypt:[EnercryTool A:names] theIdentityNumberPara:identifity twoEncrypt:[EnercryTool A:identifity] theProvince_namePara:MHSafeStrings(model_2.provinceName) theCity_namePara:MHSafeStrings(model_2.cityName) theCounty_namePara:MHSafeStrings(model_2.countryName) theTown_namePara:MHSafeStrings(model_2.townName) theVillageNameThPara:MHSafeStrings(model_2.villageName) thePhoneNumber:telPhone companyName:MHSafeStrings(model_2.companyName) verifyType:model_2.verify_type idName:u youP:self.ocrBase64 youP:self.ocrBase64_ completionHandle:^(verifyAdressModel *model, NSError *error) {
        [SVProgressHUD doneShow];
        [SVProgressHUD dismiss];
      
        if (model.code != 0) {
            
            NSLog(@"bak:%@",model.bak);
            
            
            SVProgressHUD.minimumDismissTimeInterval =3.0;
            [SVProgressHUD showErrorWithStatus:@"输入的信息不正确,请检查"];
            return;
        }
        
        NSLog(@"code:%ld",(long)model.code);
        
        
        NSLog(@" 数据访问成功");
        
        [userDefault setObject:model.bak forKey:@"bak"];
        
        if (index == 100) {
            InsuredInfoViewController* vc = [InsuredInfoViewController new];
            vc.title = @"参保信息";
            vc.paramSModel = model_2;
            vc.ValidationName = [self.nameText.text stringByReplacingOccurrencesOfString:@" " withString:@""];
            vc.ValidationIdNumber = [self.IDText.text stringByReplacingOccurrencesOfString:@" " withString:@""];
            vc.bak = model.bak;
            if (MHSafeStrings(wself.paramSModel.provinceName)) {
               [getPeopleID getprovinceNightSix:MHSafeStrings(wself.paramSModel.provinceName)];
            }
            [self.navigationController pushViewController:vc animated:YES];
        }else if (index == 101){
            
            quickInsuredInfoViewController *vc = [[quickInsuredInfoViewController alloc]init];
            vc.title = @"参保信息";
            vc.paramSModel = model_2;
            vc.ValidationName = [self->userModel.name stringByReplacingOccurrencesOfString:@" " withString:@""];
            vc.ValidationIdNumber = [self->userModel.idNumber stringByReplacingOccurrencesOfString:@" " withString:@""];
            vc.bak = model.bak;
            if (MHSafeStrings(wself.paramSModel.provinceName)) {
               [getPeopleID getprovinceNightSix:MHSafeStrings(wself.paramSModel.provinceName)];
            }
            [self.navigationController pushViewController:vc animated:YES];
            
            
        }
        
       
        
        
    /*
        UIStoryboard *sb  =[UIStoryboard storyboardWithName:@"Main" bundle:nil];
        ShowPicker *receive = [sb instantiateViewControllerWithIdentifier:@"ShowPicker"];
        receive.address_relation =wself.paramSModel.verify_type;
        receive.city =MHSafeStrings(wself.paramSModel.countryName);
        receive.province =MHSafeStrings(wself.paramSModel.provinceName);
        receive.county =MHSafeStrings(wself.paramSModel.cityName);
        receive.companyNew =MHSafeStrings(model_2.companyName);
        receive.photosModel = self;
        if (MHSafeStrings(wself.paramSModel.provinceName)) {
            [getPeopleID getprovinceNightSix:MHSafeStrings(wself.paramSModel.provinceName)];
        }
        
        
        receive.ValidationName = self.nameText.text;
        receive.ValidationIdNumber = self.IDText.text;
        receive.bak = model.bak;
        
        
        
        
        
        
        
        
        [self.navigationController pushViewController:receive animated:YES];
         
        
         */
         
         [[NSUserDefaults standardUserDefaults] setObject:MHSafeStrings(model_2.provinceName) forKey:@"successProvinceKankan"];
         [[NSUserDefaults standardUserDefaults] setObject:MHSafeStrings(model_2.cityName) forKey:@"successareaKankan"];
         [[NSUserDefaults standardUserDefaults] setObject:MHSafeStrings(model_2.countryName) forKey:@"successdowntownKankan"];
         [[NSUserDefaults standardUserDefaults] setObject:MHSafeStrings(model_2.townName) forKey:@"successTownKankan"];
         [[NSUserDefaults standardUserDefaults] setObject:MHSafeStrings(model_2.villageName) forKey:@"successDowntownKankan"];

        
        [getPeopleID socialSate:1];
        [[NSNotificationCenter defaultCenter] postNotificationName:@"ZLAuthenticationAssistant" object:nil userInfo:nil];
     
    }];



}

//初始化UIdata
- (void)clearText
{
    self.nameText.text = @"";
    self.IDText.text = @"";
    self.IDText.enabled = YES;
    
    [self textFiledName:nil];
    
}


- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    if ([segue.identifier isEqualToString:@"GCDSegue"])  {
        
        
        pickerViewController *blueVC = segue.destinationViewController;
        blueVC.OCRData =self.ocrBase64;
        blueVC.OCRData_ =self.ocrBase64_;
        for (int i = 0; i < 31; i++) {
            blueVC.array2[i] =self.baochunShuZu[i];
    
        }
    }
    if ([segue.identifier isEqualToString:@"successSegueTwo"])  {
        
        
        successViewController *blueVC = segue.destinationViewController;
        blueVC.numberInr =153;
        blueVC.GGtime =ggtime;
        blueVC.GGaddress =ggaddress;
        blueVC.GGImage =ggimage;
        blueVC.name = [name stringByReplacingOccurrencesOfString:@" " withString:@""];
        blueVC.idNumber = [idNumber stringByReplacingOccurrencesOfString:@" " withString:@""];
        blueVC.bak = [bak stringByReplacingOccurrencesOfString:@" " withString:@""];
        
        blueVC.province = province;
        blueVC.city = city;
        blueVC.county = county;

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


- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    
   
}

 WEBS
-(void)buttonClick_1{    ZHINENGKEFU}
- (void)viewDidLoad {
    [super viewDidLoad];

   
     [_collectionView registerNib:[UINib nibWithNibName:@"RZUserCollectionViewCell" bundle:nil] forCellWithReuseIdentifier:@"userCell"];
    
    
    
    
    
    
    UIButton * button_2 = [UIButton buttonWithType:UIButtonTypeCustom];        button_2.frame = CGRectMake(0, 0, 0, 49);     button_2.titleLabel.textAlignment =NSTextAlignmentRight;   [button_2 setTitle:@"     帮助" forState:UIControlStateNormal];        [button_2 addTarget:self action:@selector(buttonClick_1) forControlEvents:UIControlEventTouchUpInside];        UIBarButtonItem * backButtonItem_2 = [[UIBarButtonItem alloc] initWithCustomView:button_2];        self.navigationItem.rightBarButtonItem = backButtonItem_2;
    self.button_xieyi.selected = YES;
    self.leftContrainst.constant = [UIScreen mainScreen].bounds.size.width *90 /375;
    if ([UIScreen mainScreen].bounds.size.width == 375 ) {
        self.leftContrainst.constant  = 73;
    }else if ([UIScreen mainScreen].bounds.size.width == 320){
        self.leftContrainst.constant  = 63;
    }else if ([UIScreen mainScreen].bounds.size.width == 414){
       self.leftContrainst.constant  = 83;
    }
    //[self getOCR];
     self.PhotoBtn.userInteractionEnabled =NO;
     self.searchButton2.userInteractionEnabled =NO;
 

 
  


    self.hideView.hidden =YES;
    self.nameText.delegate=self;
    self.IDText.delegate=self;
    self.PhotoBtn.layer.cornerRadius = 5;
    self.searchButton2.layer.cornerRadius=5;
    [self.PhotoBtn addTarget:self action:@selector(photo) forControlEvents: UIControlEventTouchUpInside];
    

    
    
    
    [self.view addSubview:self.topView];
    
   
  
    
    
    
     self.navigationItem.backBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"返回" style:UIBarButtonItemStylePlain target:nil action:nil];
    
   
    
    if (kiPhone4s) {
        self.lb_middleMessageTopLayoutConstraint.constant = 0;
        self.btn_getIdInfo.titleLabel.font = [UIFont systemFontOfSize:12];
        self.backImgTopLayoutConstraint.constant = -150;
        self.photoBtnTopLayoutConstraint.constant = 9;
    }else if (kiPhone5){
        self.lb_middleMessageTopLayoutConstraint.constant = 10;
        self.btn_getIdInfo.titleLabel.font = [UIFont systemFontOfSize:12];
        self.backImgTopLayoutConstraint.constant = -140;
        self.photoBtnTopLayoutConstraint.constant = 19;
    }
    
    
    
    /*
     WeakSelf
    NSString *key = [NSString stringWithFormat:@"EmergencyContanctPeopleuserId%ld",[getPeopleID PeopleID]];
    
    bool success = [[NSUserDefaults standardUserDefaults]boolForKey:key];
    if (!success) {
        [EmergencyContactPeople showWithViewController:self Callback:^(NSInteger index, NSString * _Nonnull name, NSString * _Nonnull phone) {
                   
                   if (index == 200) {
                       [weakSelf.navigationController popViewControllerAnimated:YES];

                   }else if (index == 300){
                       [weakSelf commitEmergencyContanctPeopleWith:name phone:phone];
                       
                      
                   }
                   
        }];
    }
     */
    

    
}




-(void)goBackAction{
    
    
    [self.navigationController popViewControllerAnimated:YES];
    
}



#pragma mark - 显示认证最新成功对象
- (void)showUser
{
    NSDictionary *dic = [[NSUserDefaults standardUserDefaults]objectForKey:@"ValidationDic"];
    NSString *ValidationName = dic[@"ValidationName"];
    if (![NSString blankString:ValidationName]) {
        
        self.topView.hidden = YES;
        self.topConstant.constant = 5 * WIDTHRADIU;
        
        self.lb_left.text = [NSString stringWithFormat:@"%@刚刚认证成功",ValidationName];
    }else{
        
         self.topView.hidden = YES;
        self.topConstant.constant = 5 * WIDTHRADIU;
    }
}




- (IBAction)returnBtn:(UIButton *)sender {
    
    [self dismissViewControllerAnimated:YES completion:nil];
}

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

}

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




-(void)photo{
}









#pragma 黄


- (NSString*)dictionaryToJson:(NSDictionary *)dic

{
    
    NSError *parseError = nil;
    
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dic options:NSJSONWritingPrettyPrinted error:&parseError];
    
    return [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    
}



- (IBAction)actionSender:(id)sender {
    
    
    
    timeForButtonCount *times=[[timeForButtonCount alloc]initMustTakeReturn:nil];
    [times methodWithTimeCount:sender];
    
//    WeakSelf;
    
    
    
    
    [self getDataCompleteHandle:100];

    
    
    
}






- (IBAction)searchSocial:(id)sender {
    
    NSString *path =@"";
    path  = [IPDIZHI stringByAppendingString:@"/socialsecurity/kankan/verify"];
    
NSString *newStr = [self.IDText.text  stringByReplacingOccurrencesOfString:@" " withString:@""];
    NSLog(@"%@",newStr);
    [CityNetManager  getverifyToThePathandUserName:[getPeopleID PeopleID] andPath:path FortheName:self.nameText.text theIdentityNumberPara:newStr completionHandle:^(verifyAdressModel *model, NSError *error) {
        if (error) {
            if ([error.domain isEqualToString:@"NSURLErrorDomain"]) {
                SVProgressHUD.minimumDismissTimeInterval =2.0;
                [SVProgressHUD showErrorWithStatus:@"网络连接超时"];
                return;
            }
        }

     codeSelected *code = [codeSelected MustTakeReturn:model.code];
        [code returnCodeMethod];
        if(model.code == 0){
            
            [self performSegueWithIdentifier:@"successSegueTwo" sender:self];
            
        }
        
    }];
    
}





- (IBAction)explainIdentifly:(id)sender {
    
            SCCaptureCameraController *con = [[SCCaptureCameraController alloc] init];
            con.scNaigationDelegate = self;
            con.iCardType = TIDCARD2;
            con.isDisPlayTxt = NO;
            //con.TimeKey = TimeKeyS;
            con.ScanMode = TIDC_SCAN_MODE;
    self.searchButton2.userInteractionEnabled =YES;
    self.PhotoBtn.userInteractionEnabled=YES;
    self.PhotoBtn.backgroundColor =[UIColor colorWithRed:25/255.0 green:149/255.0 blue:109/255.0 alpha:1.0];
    self.searchButton2.backgroundColor =[UIColor colorWithRed:25/255.0 green:149/255.0 blue:109/255.0 alpha:1.0];
            [self presentViewController:con animated:YES completion:NULL];
    
    
    
}
-(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

    


}

//- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField{
//
//
//
//    if (_isEnter == YES   ) {
//
//
//    }else{
//         [self alertSHOW:@"请拍身份证正面"];
//    }
//    return YES;
//
//}
//开始编辑的时候调用

- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField
{
    if (_IDText.text.length == 0 || [_IDText.text isEqualToString:@""]) {
        if (_isEnter == YES   ) {
            
            
        }else{
            
            [self alertSHOW:@"请拍身份证正面"];
            
            return NO;
        }
    }
    
    return YES;
}

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

                    }
            }

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

//东西 -
- (IBAction)textFiledName:(UITextField *)sender {
     [self.view reloadInputViews];
      SVProgressHUD.minimumDismissTimeInterval =2.0;
      
        if ((self.nameText.text.length > 0) && (self.IDText.text.length > 3) && (self.button_xieyi.selected ==YES)) {

            self.PhotoBtn.backgroundColor =[UIColor colorWithRed:25/255.0 green:149/255.0 blue:109/255.0 alpha:1.0];
            self.searchButton2.backgroundColor =[UIColor colorWithRed:25/255.0 green:149/255.0 blue:109/255.0 alpha:1.0];
            self.PhotoBtn.userInteractionEnabled =YES;
            self.searchButton2.userInteractionEnabled =YES;
            self.backgurardView.image =[UIImage imageNamed:@"textFieldBackGuard"];
            self.hideView.hidden =YES;
            
           
        }else {
            if (self.nameText.text.length == 0 && self.IDText.text.length == 0 ) {
                
                self.hideView.hidden = YES;
                self.backgurardView.image =[UIImage imageNamed:@"textFieldBackGuard"];
                self.PhotoBtn.backgroundColor =[UIColor colorWithRed:191/255.0 green:191/255.0 blue:191/255.0 alpha:1.0];
                self.searchButton2.backgroundColor =[UIColor colorWithRed:191/255.0 green:191/255.0 blue:191/255.0 alpha:1.0];
                self.PhotoBtn.userInteractionEnabled =NO;
                self.searchButton2.userInteractionEnabled =NO;
            }else if(self.nameText.text.length > 0)
            {
                self.hideView.hidden = YES;
                self.backgurardView.image =[UIImage imageNamed:@"textFieldBackGuard"];
                self.PhotoBtn.backgroundColor =[UIColor colorWithRed:191/255.0 green:191/255.0 blue:191/255.0 alpha:1.0];
                self.searchButton2.backgroundColor =[UIColor colorWithRed:191/255.0 green:191/255.0 blue:191/255.0 alpha:1.0];
                self.PhotoBtn.userInteractionEnabled =NO;
                self.searchButton2.userInteractionEnabled =NO;
            }else{
            self.PhotoBtn.backgroundColor =[UIColor colorWithRed:191/255.0 green:191/255.0 blue:191/255.0 alpha:1.0];
            self.searchButton2.backgroundColor =[UIColor colorWithRed:191/255.0 green:191/255.0 blue:191/255.0 alpha:1.0];
            self.PhotoBtn.userInteractionEnabled =NO;
            self.searchButton2.userInteractionEnabled =NO;
            self.backgurardView.image =[UIImage imageNamed:@"textFieldBackGuardRed"];
            self.hideView.hidden =NO;
            }
        }
}
- (void)sendIDCValue:(NSString *)name SEX:(NSString *)sex FOLK:(NSString *)folk BIRTHDAY:(NSString *)birthday ADDRESS:(NSString *) address NUM:(NSString *)num
{
    self.nameText.text =name;
   
    if (![IDCardNumber_Validate isValidateIDCardString:num]) {
        [SVProgressHUD showInfoWithStatus:@"身份证识别错误,请重新拍摄"];
        return;
    }else{
        self.nameText.userInteractionEnabled = YES;
    }
    NSString *st1 =[num substringWithRange:NSMakeRange(0, 6)];
    NSString *st2 =[num substringWithRange:NSMakeRange(6, 4)];
    NSString *st3 =[num substringWithRange:NSMakeRange(10, 4)];
    NSString *st4 =[num substringFromIndex:14];
    self.IDText.text =  [NSString stringWithFormat:@"%@ %@ %@ %@",st1,st2,st3,st4];
    self.IDText.enabled = NO;//(扫描完身份证之后身份证号码不让修改,19年5月16号改...)
    if (![name isEqualToString:@""]) {
        self.isEnter = YES;
 }
}

- (void)sendAllValue:(NSString *)text
{
    NSLog(@"all  = %@",text);
    
}
- (void)sendIDCBackValue:(NSString *)issue PERIOD:(NSString *) period
{
    NSLog(@"idcback  = %@\n%@\n",issue,period);
}
- (void)sendCardFaceImage:(UIImage *)image
{
    if (image != NULL) {

        NSData *small = UIImagePNGRepresentation(image);
        
        self.ocrBase64_ = [small base64EncodedStringWithOptions:0];
    }

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

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


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

}
- (void)sendIDCARDBackAction
{
    
}
- (UIImage*)imageByScalingAndCroppingForSize:(CGSize)targetSize and:(UIImage*)imageKs
{
    UIImage *sourceImage = imageKs;
    UIImage *newImage = nil;
    CGSize imageSize = sourceImage.size;
    CGFloat width = imageSize.width;
    CGFloat height = imageSize.height;
    CGFloat targetWidth = targetSize.width;
    CGFloat targetHeight = targetSize.height;
    CGFloat scaleFactor = 0.0;
    CGFloat scaledWidth = targetWidth;
    CGFloat scaledHeight = targetHeight;
    CGPoint thumbnailPoint = CGPointMake(0.0,0.0);
    
    if (CGSizeEqualToSize(imageSize, targetSize) == NO)
    {
        CGFloat widthFactor = targetWidth / width;
        CGFloat heightFactor = targetHeight / height;
        
        if (widthFactor > heightFactor)
            scaleFactor = widthFactor;
        else
            scaleFactor = heightFactor;
        scaledWidth= width * scaleFactor;
        scaledHeight = height * scaleFactor;
        
      
        if (widthFactor > heightFactor)
        {
            thumbnailPoint.y = (targetHeight - scaledHeight) * 0.5;
        }
        else if (widthFactor < heightFactor)
        {
            thumbnailPoint.x = (targetWidth - scaledWidth) * 0.5;
        }
    }
    
    //UIGraphicsBeginImageContext(targetSize);
    UIGraphicsImageRenderer*re=[[UIGraphicsImageRenderer alloc] initWithSize:targetSize];
    CGRect thumbnailRect = CGRectZero;
    thumbnailRect.origin = thumbnailPoint;
    thumbnailRect.size.width= scaledWidth;
    thumbnailRect.size.height = scaledHeight;
    
    [sourceImage drawInRect:thumbnailRect];
    
    newImage = UIGraphicsGetImageFromCurrentImageContext();
    if(newImage == nil)
    
 
    UIGraphicsEndImageContext();
    return newImage;
}




- (IBAction)ViewController1UnwindSegue:(UIStoryboardSegue *)unwindSegue {
    if ([unwindSegue.identifier isEqualToString:@"from2to1"]) {

    }
}
- (IBAction)pushHelloWorld:(UIStoryboardSegue *)unwindSegue {
    if ([unwindSegue.identifier isEqualToString:@"unwindB"]) {
        
    }
}
- (IBAction)KankanXieYi:(id)sender {
    UIStoryboard *sb  =[UIStoryboard storyboardWithName:@"Main" bundle:nil];
    kankanshebaoxieyi *kankan = [sb instantiateViewControllerWithIdentifier:@"kankanshebaoxieyi"];
    kankan.hidesBottomBarWhenPushed =YES;
    [self.navigationController pushViewController:kankan animated:YES];
    
    
    
}

- (IBAction)ssssselfe:(id)sender {
    self.button_xieyi.selected = !self.button_xieyi.selected;
    [self textFiledName:nil];
    
}







-(void)alertSHOW:(NSString*)str{
    
    __weak __typeof(self)weakSelf = self;
    UIAlertController *alertCon =[UIAlertController alertControllerWithTitle:str message:nil preferredStyle:UIAlertControllerStyleAlert];
    if ([str isEqualToString:@"请拍身份证正面"]) {
        [alertCon addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
              
        }]];
        [alertCon addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            [weakSelf explainIdentifly:nil];
        }]];
        
    }else if ([str isEqualToString:@"是否新增用户"]){
        [alertCon addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
              
        }]];
        [alertCon addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            if ([getPeopleID getpeopleLimited]  ==YES){
                UIStoryboard *sb = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
                socialOnceViewController *once  = [sb instantiateViewControllerWithIdentifier:@"socialOnceViewController"];
                once.personPrivate =1;
                once.offLineGather =@"";
                once.name_xin = self.nameText.text;
                once.id_xin =self.IDText.text;
                once.ocrBase64 = self.ocrBase64;
                once.ocrBase64_ = self.ocrBase64_;
                once.CAOCAOCAO =@"我是皮卡丘";
                once.hidesBottomBarWhenPushed =YES;
                [weakSelf.navigationController pushViewController:once animated:NO];
            }else{
                  [SVProgressHUD showErrorWithStatus:@"请联系当地社保局"];
            }
        }]];
    }else if ([str isEqualToString:@"信息未采集,请采集"]){
        [alertCon addAction:[UIAlertAction actionWithTitle:@"下次再说" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
              
        }]];
        [alertCon addAction:[UIAlertAction actionWithTitle:@"是" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                UIStoryboard *sb = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
                socialOnceViewController *once  = [sb instantiateViewControllerWithIdentifier:@"socialOnceViewController"];
                once.personPrivate =1;
                once.offLineGather =@"";
                once.name_xin = self.nameText.text;
                once.id_xin =self.IDText.text;
                once.ocrBase64 = self.ocrBase64;
                once.ocrBase64_ = self.ocrBase64_;
                once.CAOCAOCAO =@"我是皮卡丘";
                once.hidesBottomBarWhenPushed =YES;
                [weakSelf.navigationController pushViewController:once animated:NO];
            
        }]];
    }else if ([str isEqualToString:@"该用户当天已认证成功"]) {
        [alertCon addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            
        }]];
        
    }
     [self presentViewController:alertCon animated:YES completion:nil];
    
    return;
   
    [alertCon addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
           dispatch_async(dispatch_get_main_queue(), ^{
        if ([str isEqualToString:@"请拍身份证正面"] ) {
            
           

                [weakSelf explainIdentifly:nil];
         
            
        }else if([str isEqualToString:@"是否新增用户"] ||[str isEqualToString:@"请进行社保采集"] ){
            if ([getPeopleID getpeopleLimited]  ==YES){
                UIStoryboard *sb = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
                socialOnceViewController *once  = [sb instantiateViewControllerWithIdentifier:@"socialOnceViewController"];
                once.personPrivate =1;
                once.offLineGather =@"";
                once.name_xin = self.nameText.text;
                once.id_xin =self.IDText.text;
                once.ocrBase64 = self.ocrBase64;
                once.ocrBase64_ = self.ocrBase64_;
                once.CAOCAOCAO =@"我是皮卡丘";
                once.hidesBottomBarWhenPushed =YES;
                [self.navigationController pushViewController:once animated:NO];
            }else{
                  [SVProgressHUD showErrorWithStatus:@"请联系当地社保局"];
            }
        
        
            
        }
                           
                              });
    }]];
    [self presentViewController:alertCon animated:YES completion:nil];
    
}





-(void)qitalaojiLAOZUO:(CityModel*)model andName:(NSString*)name{
      __weak __typeof(self)weakSelf = self;
    UIAlertController *alertCon =[UIAlertController alertControllerWithTitle:@"姓名与系统不一致" message:nil preferredStyle:UIAlertControllerStyleAlert];
  
    [alertCon addAction:[UIAlertAction actionWithTitle:@"修改" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
    }]];
    [alertCon addAction:[UIAlertAction actionWithTitle:@"正确" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
        dispatch_async(dispatch_get_main_queue(), ^{
            UIAlertController *alertCons =[UIAlertController alertControllerWithTitle:@"是否重新录入个人信息" message:nil preferredStyle:UIAlertControllerStyleAlert];
            
            [alertCons addAction:[UIAlertAction actionWithTitle:@"否" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                weakSelf.nameText.text = MHSafeStrings(name);
            }]];
            [alertCons addAction:[UIAlertAction actionWithTitle:@"是" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    
                    
                    if ([getPeopleID getpeopleLimited]  ==YES){
                        UIStoryboard *sb = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
                        socialOnceViewController *once  = [sb instantiateViewControllerWithIdentifier:@"socialOnceViewController"];
                        once.personPrivate =1;
                        once.offLineGather =@"";
                        once.name_xin = weakSelf.nameText.text;
                        once.id_xin =weakSelf.IDText.text;
                        once.CAOCAOCAO =@"我是皮卡丘";
                        once.hidesBottomBarWhenPushed =YES;
                        [weakSelf.navigationController pushViewController:once animated:NO];
                    }else{
                        [SVProgressHUD showErrorWithStatus:@"请联系当地社保局"];
                    }
                    
                    
                });
            }]];
              [weakSelf presentViewController:alertCons animated:YES completion:nil];
            
            
            
            
        });
    }]];
    [self presentViewController:alertCon animated:YES completion:nil];
    
}


#pragma mark - UICollectionViewDataSource
- (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];
    
    
    if (userModel.timeStamp && [self isSameDay:[self UTCDateFromTimeStamap:userModel.timeStamp] date2:[NSDate date]]) {
        [self alertSHOW:@"该用户当天已认证成功"];
    }else{
        [self getDataCompleteHandle:101];
    }
    
    
    
    
    
}




#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_rzUser (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_rzUser"]){
                NSString *alertStr = [NSString stringWithFormat:@"ALTER TABLE %@ ADD %@ text",@"t_rzUser",@"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_rzUser 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 = [EnercryTool desA:name];
            model.idNumber = [EnercryTool desA: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) {
        [self removeUserListUI];
    }else{
        [self hiddenCollection:NO];
        [self.collectionView reloadData];
    }
    
    
}


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

}




#pragma mark - 移除用户列表
-(void)removeUserListUI
{
    
    [self hiddenCollection:YES];
    
//    [self.collectionView removeFromSuperview];
//    [self.lb_middleMessage removeFromSuperview];
//    [self.leftLine removeFromSuperview];
//    [self.rightLine removeFromSuperview];
}

#pragma mark - 隐藏或显示collectionview
- (void)hiddenCollection:(BOOL)hidden
{
   
    self.collectionView.hidden = hidden;
    self.lb_middleMessage.hidden = hidden;
    self.leftLine.hidden = hidden;
    self.rightLine.hidden = hidden;
   
    if (hidden) {
        self.photoBtnAndImgTopLayoutConstraint.constant = 38.5;
    }else{
        self.photoBtnAndImgTopLayoutConstraint.constant = 120.8;
    }

    
        
}

#pragma mark - 填写紧急联系人请求
- (void)commitEmergencyContanctPeopleWith:(NSString*)name phone:(NSString *)phone
{
    NSDictionary *dic = @{
        @"name":[EnercryTool A:[name stringByReplacingOccurrencesOfString:@" " withString:@""]],
        @"phone":[EnercryTool A:[phone stringByReplacingOccurrencesOfString:@" " withString:@""]]
    };
    
    NSMutableArray* array = [NSMutableArray array];
    
    [array addObject:dic];
    
   NSString* result = [self ObjectToJsonString:array];
    
    [SVProgressHUD shows];
    [CityNetManager tongxunlu:result completionHandle:^(verifyAdressModel* model, NSError *error) {
        [SVProgressHUD doneShow];
        [SVProgressHUD dismiss];
        if (error) {
            
            return;
        }
        
        if (model.code == 0) {
            NSString *key = [NSString stringWithFormat:@"EmergencyContanctPeopleuserId%ld",[getPeopleID PeopleID]];
            [[NSUserDefaults standardUserDefaults]setBool:YES forKey:key];
            [[NSUserDefaults standardUserDefaults]synchronize];
          
            return;
        }
        
    }];
    
}
#pragma mark - 对象转json
-(NSString*)ObjectToJsonString:(id)object{
    NSString *jsonString = [[NSString
                             alloc]init];
    NSError *error;
    NSData *jsonData = nil;
    if (object) {
        jsonData = [NSJSONSerialization
                    
                    
                    
                    dataWithJSONObject:object
                    
                    
                    
                    options:NSJSONWritingPrettyPrinted
                    
                    
                    
                    error:&error];
    }
    
    
    
    if (! jsonData) {
        
        NSLog(@"error: %@", error);
        
        
        
        
    } else {
        
        
        
        jsonString = [[NSString
                       
                       
                       
                       alloc] initWithData:jsonData
                      
                      
                      
                      encoding:NSUTF8StringEncoding];
        
        
        
    }
    
    
    
    NSMutableString *mutStr = [NSMutableString
                               
                               
                               
                               stringWithString:jsonString];
    
    
    
    NSRange range = {0,jsonString.length};
    
    
    
    [mutStr replaceOccurrencesOfString:@" "
     
     
     
                            withString:@""
     
     
     
                               options:NSLiteralSearch range:range];
    
    
    
    NSRange range2 = {0,mutStr.length};
    
    
    
    [mutStr replaceOccurrencesOfString:@"\n"
     
     
     
                            withString:@""
     
     
     
                               options:NSLiteralSearch range:range2];
    
    NSRange range3 = {0, mutStr.length};
    
    NSString * str = @"\\";
    
    [mutStr replaceOccurrencesOfString:str withString:@"" options:NSLiteralSearch range:range3];
    
    
    
    return jsonString;
    
}

#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 - event response
- (void)checkBtnClick:(UIButton *)sender
{
    UIStoryboard *sb  =[UIStoryboard storyboardWithName:@"Main" bundle:nil];
    
    socialRecord*vc=[sb instantiateViewControllerWithIdentifier:@"socialRecord"];
    
    vc.isHomeVC = YES;
    vc.hidesBottomBarWhenPushed =YES;
    [self.navigationController pushViewController:vc animated:YES];
}



#pragma mark - getters and setters
- (UIView *)topView
{
    if (!_topView) {
        _topView = [[UIView alloc]initWithFrame:CGRectMake(0, cl_kNavigationBarHeight, ScreenWidth, 30 * WIDTHRADIU)];
        _topView.backgroundColor = [UIColor colorWithHex:0x32b070];
        [_topView addSubview:self.img_loudspeaker];
        [_topView addSubview:self.lb_left];
        [_topView addSubview:self.btn_right];
        [self settopViewUI];
        _topView.hidden = YES;
    }
    return _topView;
}

- (void)settopViewUI{
    [self.img_loudspeaker mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(self.topView);
        make.left.offset(10 * WIDTHRADIU);
    }];
    [self.lb_left mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(self.img_loudspeaker);
        make.left.equalTo(self.img_loudspeaker.mas_right).offset(5 * WIDTHRADIU);
    }];
    
    [self.btn_right mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(self.img_loudspeaker);
        make.right.offset(- 10 * WIDTHRADIU);
    }];
}

- (UIImageView *)img_loudspeaker
{
    if (!_img_loudspeaker) {
        _img_loudspeaker = [[UIImageView alloc]init];
        _img_loudspeaker.image = [UIImage imageNamed:@"通知icon"];
    }
    return _img_loudspeaker;
}

- (UILabel *)lb_left
{
    if (!_lb_left) {
        _lb_left = [[UILabel alloc]init];
        _lb_left.textColor = [UIColor whiteColor];
        _lb_left.font = [UIFont systemFontOfSize:12 * WIDTHRADIU];
    }
    return _lb_left;
}

- (UIButton *)btn_right
{
    if (!_btn_right) {
        _btn_right = [UIButton buttonWithType:UIButtonTypeCustom];
        [_btn_right setTitle:@"查看更多>>" forState:UIControlStateNormal];
        _btn_right.titleLabel.font = [UIFont systemFontOfSize:12 * WIDTHRADIU];
        [_btn_right setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [_btn_right addTarget:self action:@selector(checkBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _btn_right;
}

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












@end
