//
//  socialSecurityViewController.m
//  Open
//
//  Created by 看看智能 on 2017/2/15.
//  Copyright © 2017年 黄江涛 . All rights reserved.
//

#import "socialSecurityViewController.h"

#import "GreenChannelVC.h"







@interface socialSecurityViewController ()<UITextFieldDelegate,UIScrollViewDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate,SCNavigationControllerDelegate>

//创建一个只读属性
@property(nonatomic,assign)NSInteger justReadNumber;

@property(nonatomic,strong)UIView *view_f;
@end


static NSString *static_province;
static NSString *static_city;
static NSString *static_country;
static NSString *static_numberPro;
static NSString *static_numbercity;
static NSString *static_numbercountry;

#define MHSafeString(str) (str == nil ? @"" : str)
@implementation socialSecurityViewController
//scrollView的代理方法
- (void)updateViewConstraints {
    [super updateViewConstraints];
    //设置为两个屏幕的宽度
   

}

-(UIButton *)buttonforclick
{
    if (!_buttonToSenderPhoto) {
//        _buttonToSenderPhoto=[UIButton buttonWithType:0];
//        _buttonToSenderPhoto.frame=CGRectMake(0,self.photocamera.frame.origin.y+20, self.view.bounds.size.width, 50);
//        [_buttonToSenderPhoto setTitle:@"传照片" forState:UIControlStateNormal];
           _buttonforclick.layer.cornerRadius=5.0;
//            _buttonToSenderPhoto.backgroundColor =[UIColor colorWithRed:191/255.0 green:191/255.0 blue:191/255.0 alpha:1.0];
    }
    return _buttonforclick;


}

- (UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView
{
    return self.totalView;
}
-(void)contraintChangeOne
{
    self.heightVillageContraint.constant = 40;
    self.topVillageContraint.constant =10;
       self.heightVillageCommitteeContraint.constant =40;
    self.topVillageCommittee.constant =10;
 
    self.topLabelCommiteeConstraint.constant =30;
    self.topLabelCommitteeConstraint2.constant =30;
    self.heightLalCommittee.constant =21;
    self.heightLabelCommittee2.constant =21;
  self.labelxiang.text =@"乡镇";
     self.juweihui.text =@"村委会";
}


-(void)contraintChangeTwo
{
    self.heightVillageContraint.constant = 0;
    self.topVillageContraint.constant =0;
    self.topVillageCommittee.constant =0;
    self.heightVillageCommitteeContraint.constant =0;
    self.topLabelCommiteeConstraint.constant =0;
    self.topLabelCommitteeConstraint2.constant =0;
    self.heightLalCommittee.constant =0;
    self.heightLabelCommittee2.constant =0;

    if(![self.offLineGather isEqualToString:@"离线采集"]) {   self.labelxiang.text =@"";
        self.juweihui.text =@"";}
}


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

//懒加载
-(NSMutableArray *)arrayForCity
{
    if (!_arrayForCity) {
        _arrayForCity =[NSMutableArray new];
        [_arrayForCity removeAllObjects];
    }
    return _arrayForCity;
}


//懒加载
-(NSMutableArray *)array
{
    if (!_array) {
        _array =[NSMutableArray new];
        
    }
    return _array;
}
-(NSMutableArray *)array0
{
    if (!_array0) {
        _array0 =[NSMutableArray new];
        
    }
    return _array0;
}
//+ (instancetype)shareInstance {
//    static pickerViewController *_pickViewController = nil;
//    static dispatch_once_t oncePredicate;
//    dispatch_once(&oncePredicate, ^{
//        _pickViewController = [[self alloc] init];
//    });
//    return _pickViewController;
//}




-(NSMutableArray *)array2
{
    if (!_array2 ) {
        _array2 =[NSMutableArray array];
        
    }
    return _array2;
    
}



#pragma mark-这里发送第一个地址
-(void)getProvinceMessage
{
    
    NSString *path =[IPDIZHI stringByAppendingString:@"/socialsecurity/kankan/getProvince"];
    NSLog(@"%@",path);
    NSString *NameEnerypt =  [EnercryTool A:@"黄江涛"];
    NSString *IdentiftyEnerypt = [EnercryTool A:@"42112619940907171X"];
    [CityNetManager getMoreCityForThisMethod:@"name" encrypt:NameEnerypt andTheOther:@"identityNumber" twoEncrypt:IdentiftyEnerypt  andPutThePathForThis:path andID:[getPeopleID PeopleID] completionHandle:^(CityModel *model, NSError *error) {
        if(error){
            [SVProgressHUD showErrorWithStatus:@"服务器无法连接"];
            return;
        }
        [self.array0 addObjectsFromArray:model.result];
        //内部版把30 改成31
        for (int row = 0 ; row < 31 ; row++) {
            
            if (self.array0 == nil) {
                return;
            }
            
            CityResultModel *city =self.array0[row];
            [self.array2 addObject:city.provice_name];
            
            NSData *data =[NSKeyedArchiver archivedDataWithRootObject:city.provice_id];
            
            [self.dataArr addObject:data];
            NSLog(@"%@",self.dataArr[row]);
            
            NSLog(@"huangjiangtao:%@",self.array2[row]);
            
        }
        NSUserDefaults *userDefaults =[NSUserDefaults standardUserDefaults];
        [userDefaults setObject:self.dataArr forKey:@"myPrivinceModel"];
        [userDefaults synchronize];
        [self  savensuserDefault ];
      
        
        
        
    }];
    
    
    
}
-(NSMutableArray *)ocrImageArray
{
    if (_ocrImageArray) {
        _ocrImageArray =[[NSMutableArray alloc]init];
    }
    return _ocrImageArray;
}
-(void)savensuserDefault
{
    NSUserDefaults *userDefaults =[NSUserDefaults standardUserDefaults];
    [userDefaults setObject: self.array2 forKey:@"myArray"];
    [userDefaults synchronize];
    
}
  WEBS
-(void)buttonClick_1{    ZHINENGKEFU}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title =@"选择地址";
    
    //离线采集


    
    if ([self.offLineGather isEqualToString:@"离线采集"] && self.province.text.length > 0) {
        
        UIAlertController *alertCon =[UIAlertController alertControllerWithTitle:@"第一次使用离线采集需要在有网络的情况下获取一次地址和身份" message:nil preferredStyle:UIAlertControllerStyleAlert];
        [alertCon addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {                               }]];
           [self presentViewController:alertCon animated:YES completion:nil];
    }
  
    UIButton * button_ = [UIButton buttonWithType:UIButtonTypeCustom];        button_.frame = CGRectMake(0, 0, 0, 49);     button_.titleLabel.textAlignment =NSTextAlignmentRight;   [button_ setTitle:@"     帮助" forState:UIControlStateNormal];        [button_ addTarget:self action:@selector(buttonClick_1) forControlEvents:UIControlEventTouchUpInside];        UIBarButtonItem * backButtonItem_2 = [[UIBarButtonItem alloc] initWithCustomView:button_];        self.navigationItem.rightBarButtonItem = backButtonItem_2;
    
    [self getOCR];
    [self getProvinceMessage];
//    self.scrollV.frame=CGRectMake(0, 0, self.view.bounds.size.width, 667);
//    self.scrollV.contentSize=CGSizeMake(self.view.bounds.size.width, 999);
    self.scrollV.delegate=self;
    self.scrollV.scrollEnabled= YES;
    self.scrollV.userInteractionEnabled =YES;
  //  self.scrollV.backgroundColor = [UIColor grayColor];
    self.scrollV.bounces=NO;
  
//        [self.scrollV addSubview: self.buttonToSenderPhoto];
  

    //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    
    if ([[[UIDevice currentDevice]deviceModel] isEqualToString:Device_iPhone5S] || [[[UIDevice currentDevice]deviceModel] isEqualToString:Device_iPhone5S] || [[[UIDevice currentDevice]deviceModel] isEqualToString:Device_iPhone5]) {
        self.button1.titleLabel.font =[UIFont systemFontOfSize:12];
        self.button2.titleLabel.font =[UIFont systemFontOfSize:12];
        self.button3.titleLabel.font =[UIFont systemFontOfSize:12];
    }
    if([[UIScreen mainScreen]bounds].size.height == 568)
    {
        self.button1.titleLabel.font =[UIFont systemFontOfSize:13];
        self.button2.titleLabel.font =[UIFont systemFontOfSize:13];
        self.button3.titleLabel.font =[UIFont systemFontOfSize:13];
    }
    // Do any additional setup after loading the view, typically from a nib.
   
    
    self.nameText.delegate=self;
    self.IDText.delegate =self;
    self.province.delegate =self;
    self.downTown.delegate =self;
    self.area.delegate =self;
    self.village.delegate =self;
    self.villageCommittee.delegate =self;
    self.ice =0;
   // [self textFieldAddTwoBlackPlaceinTextFiled:self.phoneNumber];
    [self textFieldAddTwoBlackPlaceinTextFiled:self.Company];
    self.province.textAlignment = NSTextAlignmentCenter;
    self.downTown.textAlignment =NSTextAlignmentCenter;
    self.area.textAlignment =NSTextAlignmentCenter;
    self.village.textAlignment =NSTextAlignmentCenter;
    self.villageCommittee.textAlignment =NSTextAlignmentCenter;
  //  self.phoneNumber.textAlignment =NSTextAlignmentCenter;
    //设置只读属性
    self.companytakenToTop.constant = 0;
    self.justReadNumber = self.buttonforclick.frame.origin.y+200;
      self.greenValue.layer.cornerRadius=5.0;
    self.scrolWidth.constant = self.justReadNumber;

   
   if (![self.offLineGather isEqualToString:@"离线采集"]) {
//       [self shezhisuoyouweiNill];
   }
    _phoneBool =NO;
    _companyBool =NO;
    self.companyViewHide.hidden =YES;
    
 
    _provinceNumber =[static_numberPro copy];
    _CityNumber =[static_numbercity copy];
    _areaNumber =[static_numbercountry copy];
       self.province.text=static_province;
    self.downTown.text =static_city;
    self.area.text =static_country;
    
    
    

    
    [self layoutSizeView];
    
    
    
}
-(void)layoutSizeView{
    //添加一个动画,渐变的效果
    self.view_f = [[UIView alloc]initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height)];
    self.view_f.backgroundColor =[UIColor colorWithRed:0.0/255.0 green:0.0/255.0 blue:0.0/255.0 alpha:0.7];
    CATransition *applicationLoadViewIn =[CATransition animation];
    [applicationLoadViewIn setDuration:0.5];
    [applicationLoadViewIn setType:kCATransitionReveal];
    [applicationLoadViewIn setTimingFunction:[CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseIn]];
    //you view need to replace
    [[self.view_f layer]addAnimation:applicationLoadViewIn forKey:kCATransitionReveal];
    [[self.ViewHiden layer]addAnimation:applicationLoadViewIn forKey:kCATransitionReveal];


    
    
    
}



-(void)shezhisuoyouweiNill
{
    dispatch_async(dispatch_get_main_queue(), ^{
        self.province.text= @"";
        self.downTown.text =@"";
        self.area.text =@"";
        self.village.text =@"";
        self.villageCommittee.text =@"";
        self.Company.text =@"";
    });

   // self.phoneNumber.text=@"";
    
    
    
    
}

//-(void)savensuserDefault
//{
//    NSUserDefaults *userDefaults =[NSUserDefaults standardUserDefaults];
//    [userDefaults setObject:self.array2 forKey:@"myArray"];
//    
//    [userDefaults synchronize];
//    
//}


-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
//     self.companytakenToTop.constant=0;
    //离线采集做一个说明
    self.greenValue.hidden =NO;
   
        self.changeThreeWithUrbanAndGovern =self.button1;
    if ([self.offLineGather isEqualToString:@"离线采集"]) {
   self.greenValue.hidden =YES;
        gatherUtil *gat = [[gatherUtil alloc]initWithGG];
       
        if ( [gat  readAddress].count ==0) {
            return;
        }else{
            self.province.text =[gat  readAddress][0];
            self.downTown.text =[gat  readAddress][1];
            self.area.text =[gat  readAddress][2];
            self.village.text =[gat  readAddress][3];
            self.villageCommittee.text =[gat  readAddress][4];
            
            
        }
        [self provinceChoose:nil];
//        UIAlertController *alertCon =[UIAlertController alertControllerWithTitle:@"离线采集第一次使用需要在有网络的情况下获取一次地址和身份" message:nil preferredStyle:UIAlertControllerStyleAlert];
//        [alertCon addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
//                               }]];
//   [self presentViewController:alertCon animated:YES completion:nil];
                             }

    
    
    
    
    

    
    
    
    
    
    
    self.nameText.text =self.nText;
    self.IDText.text =self.idText;
    self.phoneNumber.text = self.telText;
    [getPeopleID socialSate:2];
    
    if (self.paraModel.countryName.length >0  && [self.paraModelStr isEqualToString:@"asdasd"] ) {
        [self openAllMethod:NO];
        self.province.text = self.paraModel.provinceName;
         self.downTown.text =self.paraModel.cityName;
         self.area.text =self.paraModel.countryName;
         self.village.text =self.paraModel.townName;
         self.villageCommittee.text =self.paraModel.villageName;
        
//         self.phoneNumber.text =self.paraModel.provinceName;
         self.Company.text =self.paraModel.companyName;
         self.ice =self.paraModel.verify_type;
      
        switch (self.ice) {
            case 0:
                [self button_1:nil];

                break;
            case 1:
                [self button_2:nil];
                break;
            case 2:
       
                 [self button_3:nil];
                break;
            default:
                break;
        }
          [self provinceChoose:nil];
        //清空model
      
    }else{
        
        if (self.goGreenTongDao ==NO) {
            [self shezhisuoyouweiNill];
        }
         [self openAllMethod:YES];
    }
    
    
    
    
}

-(void)openAllMethod:(BOOL)bool_{
  
    self.province.userInteractionEnabled =bool_;
    self.downTown.userInteractionEnabled =bool_;
    self.area.userInteractionEnabled =bool_;
    self.village.userInteractionEnabled =bool_;
    self.villageCommittee.userInteractionEnabled =bool_;
    self.button1.userInteractionEnabled =bool_;
     self.button2.userInteractionEnabled =bool_;
     self.button3.userInteractionEnabled =bool_;
    
}





-(void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    UITapGestureRecognizer* singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleSingleTap)];
    
    [self.totalView addGestureRecognizer:singleTap];
    
    [self.view openKeyboardOffsetView];
    self.view.keyboardGap =5;
    //百度活体检测
    [[NSUserDefaults standardUserDefaults ]setInteger:1 forKey:@"huoti_kankan_int"];
    [[NSUserDefaults standardUserDefaults]synchronize];
    
    [MobClick beginLogPageView:@"社保采集-人脸提交比对"];
    [JANALYTICSService startLogPageView:@"社保采集-人脸提交比对"];
    
}
-(void)handleSingleTap{
    [self.totalView endEditing:YES];

}

- (void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];
    
    // 关闭键盘补偿视图
    [self.view closeKeyboardOffsetView];
    [MobClick endLogPageView:@"社保采集-人脸提交比对"];
    [JANALYTICSService stopLogPageView:@"社保采集-人脸提交比对"];
}


-(BOOL)textFieldShouldBeginEditing:(UITextField*)textField{
    
    [self provinceChoose:textField];
    if (textField ==self.IDText) {
            [textField resignFirstResponder];
        return YES;
    }else if(textField ==self.nameText)
    {
            [textField resignFirstResponder];
        return YES;
    }
    
    
    
    [textField resignFirstResponder];

    return NO;
}


//两个网络请求的方法
+ (AFHTTPSessionManager *)sharedAFManager{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        manager = [AFHTTPSessionManager manager];
        manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/html", @"application/json", @"text/json", @"text/javascript", @"text/plain", nil];
    });
    return manager;
}





#define mark -这里showpicker
- (HXProvincialCitiesCountiesPickerview *)regionPickerView {
    if (!_regionPickerView) {
        _regionPickerView = [[HXProvincialCitiesCountiesPickerview alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)];
        
        __weak typeof(self) wself = self;
        _regionPickerView.completion = ^(NSString *provinceName,NSString *numberSign,NSString *countyName) {
            __strong typeof(wself) self = wself;
            self.addressLabel.text = [NSString stringWithFormat:@"%@",provinceName,nil,nil];


            if (indexTag == 1 ){
                
                //                _provinceName =provinceName;
                
                _provinceNumber =numberSign;
                self.province.text =provinceName;
                //静态
                static_province =self.province.text;
                static_numberPro =numberSign;
                //              self.numbertag =numberSign;
                self.downTown.text =0;
                self.area.text =0;
                self.village.text =0;
                self.villageCommittee.text =0;
             //   self.phoneNumber.text = 0;
                self.Company.text = 0;
            }
            if(indexTag == 2){
                //                _CityName =provinceName;
                _CityNumber =numberSign;
                self.downTown.text =provinceName;
                //静态
                static_city =provinceName;
                static_numbercity =numberSign;
                self.area.text =0;
                self.village.text =0;
                self.villageCommittee.text =0;
               // self.phoneNumber.text = 0;
                self.Company.text = 0;
            }
            if (indexTag == 3) {
                self.area.text =provinceName;
                _areaNumber =numberSign;
                //静态
                static_numbercountry =numberSign;
                static_country =provinceName;
//                static_number =numberSign;
                self.village.text =0;
                self.villageCommittee.text =0;
              //  self.phoneNumber.text = 0;
                self.Company.text = 0;
                
            }
            if (indexTag == 4) {
                self.village.text =provinceName;
                self.villageCommittee.text =0;
            //    self.phoneNumber.text = 0;
                self.Company.text = 0;
                _TownNumber =numberSign;
                NSLog(@"chengshi:%@",_TownNumber);
                NSLog(@"chengshi:%@",self.village.text);
            }
            if (indexTag == 5 ) {
                self.villageCommittee.text =provinceName;
                _VillageCoNumber =numberSign;
            //    self.phoneNumber.text = 0;
                self.Company.text = 0;
            }
        };
        [self.navigationController.view addSubview:_regionPickerView];
    }
    return _regionPickerView;
}

- (void)show:(UITextField *)sender {
    NSString *address = _addressLabel.text;
    //用空格来分割字符串
    NSArray *array = [address componentsSeparatedByString:@" "];
    
    provinceLabel = array[0];
    [self.regionPickerView showPickerWithProvinceName:provinceLabel cityName:nil countyName:nil index:1];
}

#define mark -在此发送第二个数据
static int tagger = 0 ;
static int indexTag =1;
-(void)senderSecondMessage:(NSString *)province_id theSecondMessage:(NSString *)province_name
{
//    [SVProgressHUD show];
    indexTag  = 2;
    
    NSString *name =@"province_name";
    NSString *ID =@"province_id";
    NSString *IDEn =  [EnercryTool encryptUseDES:province_id  key:@"KkweFace95271124"];
    NSString *NameEn =  [EnercryTool encryptUseDES:self.province.text key:@"KkweFace95271124"];
    NSString *path =@"";
    path  = [IPDIZHI stringByAppendingString:@"/socialsecurity/kankan/city"];
    [CityNetManager getMD5Method:name encrypt:NameEn andTheOther:ID twoEncrypt:IDEn andPutThePathForThis:path completionHandle:^(CitytoCityModel *model, NSError *error) {
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{

        if (model.result == nil) {
            SVProgressHUD.minimumDismissTimeInterval =3.0;
            if ([self.offLineGather isEqualToString:@"离线采集"])
                [self shezhisuoyouweiNill]; else
            [SVProgressHUD showErrorWithStatus:@"请重新选择省份"];
  
            
            [self.nameText shake];
            [self.IDText shake];
            [self.province shake];
            return;
        }
        [self.array removeAllObjects];
        [self.arrayForCity removeAllObjects];
        [self.dataArr removeAllObjects];
        [self.array addObjectsFromArray:model.result];
        for (CityToCityResultModel *models in self.array) {
            //保存了city数据
            [self.arrayForCity addObject:models.city_name];
            
            NSData *data =[NSKeyedArchiver archivedDataWithRootObject:models.city_id];
            [self.dataArr addObject:data];
            //保存了city_id的数据
        }
        NSArray * CityNetWorkForID = [NSArray arrayWithArray:self.dataArr];
        NSUserDefaults *userDefaults =[NSUserDefaults standardUserDefaults];
        [userDefaults setObject:CityNetWorkForID forKey:@"myCityModelID"];
        [userDefaults synchronize];
        //修改
        NSArray * CityNetWorkArray = [NSArray arrayWithArray:self.arrayForCity];
        //修改
        NSUserDefaults *userDefault =[NSUserDefaults standardUserDefaults];
        [userDefault setObject:CityNetWorkArray forKey:@"myCityModel"];
        [userDefault synchronize];
        NSString *address = _addressLabel.text;
        //用空格来分割字符串
        NSArray *array = [address componentsSeparatedByString:@" "];
        provinceLabel = array[0];
        self.regionPickerView =nil;
            dispatch_async(dispatch_get_main_queue(), ^{

//        [SVProgressHUD dismiss];
        if (tagger == 0) {
            [self.regionPickerView showPickerWithProvinceName:provinceLabel cityName:nil countyName:nil index:2];
            //                 tagger =1;
        }else
        {
            [self.regionPickerView showPickerWithProvinceName:province_name cityName:nil countyName:nil index:3];
        }
            });
        });
        NSLog(@"代码在这个线程block----%@",[NSThread currentThread]);
    }];
    NSLog(@"代码在这个线程3----%@",[NSThread currentThread]);
    
}
#define mark -在此发送第三个数据
-(void)senderCountryMessage:(NSString *)province_id theSecondMessage:(NSString *)province_name
{
//    [SVProgressHUD show];
    indexTag  =3;
    
    NSString *name =@"city_name";
    NSString *ID =@"city_id";
    NSLog(@"%@",province_id);
    NSString *IDEn =  [EnercryTool encryptUseDES:province_id  key:@"KkweFace95271124"];
    NSString *NameEn =  [EnercryTool encryptUseDES:province_name key:@"KkweFace95271124"];
    
    NSString *path =@"";
    path  = [IPDIZHI stringByAppendingString:@"/socialsecurity/kankan/county"];
    [CityNetManager getAreaMethod:name encrypt:NameEn andTheOther:ID twoEncrypt:IDEn andPutThePathForThis:path completionHandle:^(areaModel *model, NSError *error) {
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{

        if (model.result == nil) {
            SVProgressHUD.minimumDismissTimeInterval =3.0;
            if ([self.offLineGather isEqualToString:@"离线采集"])
                [self shezhisuoyouweiNill]; else
            [SVProgressHUD showErrorWithStatus:@"请重新选择城市"];
            return;
        }
        
        [self.array removeAllObjects];
        [self.arrayForCity removeAllObjects];
        [self.dataArr removeAllObjects];
        [self.array addObjectsFromArray:model.result];
        
        for (CityToAreaResultModel *models in self.array) {
            //保存了city数据
            [self.arrayForCity addObject:models.county_name];
            
            NSData *data =[NSKeyedArchiver archivedDataWithRootObject:models.county_id];
            [self.dataArr addObject:data];
            //保存了city_id的数据
        }
        NSArray * CityNetWorkForID = [NSArray arrayWithArray:self.dataArr];
        NSUserDefaults *userDefaults =[NSUserDefaults standardUserDefaults];
        [userDefaults setObject:CityNetWorkForID forKey:@"myCityModelID"];
        [userDefaults synchronize];
        //修改
        NSArray * CityNetWorkArray = [NSArray arrayWithArray:self.arrayForCity];
        //修改
        NSUserDefaults *userDefault =[NSUserDefaults standardUserDefaults];
        [userDefault setObject:CityNetWorkArray forKey:@"myCityModel"];
        [userDefault synchronize];
        NSString *address = _addressLabel.text;
        //用空格来分割字符串
        NSArray *array = [address componentsSeparatedByString:@" "];
        provinceLabel = array[0];
        self.regionPickerView =nil;
//        [SVProgressHUD dismiss];
            dispatch_async(dispatch_get_main_queue(), ^{

        [self.regionPickerView showPickerWithProvinceName:provinceLabel cityName:nil countyName:nil index:2];
            });
        });
        NSLog(@"代码在这个线程block----%@",[NSThread currentThread]);
    }];
    NSLog(@"代码在这个线程3----%@",[NSThread currentThread]);
    
}
#define mark -在此发送第四个数据
-(void)senderTownMessage:(NSString *)province_id theSecondMessage:(NSString *)province_name
{
    
    
//    [SVProgressHUD show];
    indexTag  =4;
    //    dispatch_queue_t  queue= dispatch_queue_create("wendingding", NULL);
    //线程一,串行执行
    //    dispatch_async(queue, ^{
    NSString *name =@"county_name";
    NSString *ID =@"county_id";
    NSString *IDEn =  [EnercryTool encryptUseDES:province_id  key:@"KkweFace95271124"];
    NSString *NameEn =  [EnercryTool encryptUseDES:province_name key:@"KkweFace95271124"];
    
    NSString *path =@"";
    path  = [IPDIZHI stringByAppendingString:@"/socialsecurity/kankan/town"];
    [CityNetManager getTownMethod:name encrypt:NameEn andTheOther:ID twoEncrypt:IDEn andPutThePathForThis:path completionHandle:^(Town *model, NSError *error) {
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{

        if (model.result == nil) {
            SVProgressHUD.minimumDismissTimeInterval =3.0;
            if ([self.offLineGather isEqualToString:@"离线采集"])
                [self shezhisuoyouweiNill]; else
            [SVProgressHUD showErrorWithStatus:@"请重新选择区"];
            return;
        }
        
        [self.array removeAllObjects];
        [self.arrayForCity removeAllObjects];
        [self.dataArr removeAllObjects];
        [self.array addObjectsFromArray:model.result];
        
        for (TownResultModel *models in self.array) {
            //保存了city数据
            [self.arrayForCity addObject:models.town_name];
            
            NSData *data =[NSKeyedArchiver archivedDataWithRootObject:models.town_id];
            [self.dataArr addObject:data];
            //保存了city_id的数据
        }
        NSArray * CityNetWorkForID = [NSArray arrayWithArray:self.dataArr];
        NSUserDefaults *userDefaults =[NSUserDefaults standardUserDefaults];
        [userDefaults setObject:CityNetWorkForID forKey:@"myCityModelID"];
        [userDefaults synchronize];
        //修改
        NSArray * CityNetWorkArray = [NSArray arrayWithArray:self.arrayForCity];
        //修改
        NSUserDefaults *userDefault =[NSUserDefaults standardUserDefaults];
        [userDefault setObject:CityNetWorkArray forKey:@"myCityModel"];
        [userDefault synchronize];
        NSString *address = _addressLabel.text;
        //用空格来分割字符串
        NSArray *array = [address componentsSeparatedByString:@" "];
        provinceLabel = array[0];
        self.regionPickerView =nil;
//        [SVProgressHUD dismiss];
            dispatch_async(dispatch_get_main_queue(), ^{
  
        [self.regionPickerView showPickerWithProvinceName:provinceLabel cityName:nil countyName:nil index:2];
            });
        });
        NSLog(@"代码在这个线程block----%@",[NSThread currentThread]);
    }];
    NSLog(@"代码在这个线程3----%@",[NSThread currentThread]);
    
}
#define mark -这里第五个数据
-(void)senderVillageMessage:(NSString *)province_id theSecondMessage:(NSString *)province_name
{
//    [SVProgressHUD show];
    indexTag  =5;
    
    //    dispatch_queue_t  queue= dispatch_queue_create("wendingding", NULL);
    //线程一,串行执行
    //    dispatch_async(queue, ^{
    NSString *name =@"town_name";
    NSString *ID =@"town_id";
    NSString *IDEn =  [EnercryTool encryptUseDES:province_id  key:@"KkweFace95271124"];
    NSString *NameEn =  [EnercryTool encryptUseDES:province_name key:@"KkweFace95271124"];
    NSString *path =@"";
    path  = [IPDIZHI stringByAppendingString:@"/socialsecurity/kankan/village"];
    [CityNetManager getVillageMethod:name encrypt:NameEn andTheOther:ID twoEncrypt:IDEn andPutThePathForThis:path completionHandle:^(VillageModel *model, NSError *error) {
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{

        if (model.result == nil) {
            SVProgressHUD.minimumDismissTimeInterval =3.0;
            if ([self.offLineGather isEqualToString:@"离线采集"])
                [self shezhisuoyouweiNill]; else
            [SVProgressHUD showErrorWithStatus:@"请重新选择乡镇"];
            return;
        }
        
        [self.array removeAllObjects];
        [self.arrayForCity removeAllObjects];
        [self.dataArr removeAllObjects];
        [self.array addObjectsFromArray:model.result];
        
        for (VillageResultModel *models in self.array) {
            //保存了city数据
            [self.arrayForCity addObject:models.village_name];
            
            NSData *data =[NSKeyedArchiver archivedDataWithRootObject:models.village_id];
            [self.dataArr addObject:data];
            //保存了city_id的数据
        }
        NSArray * CityNetWorkForID = [NSArray arrayWithArray:self.dataArr];
        NSUserDefaults *userDefaults =[NSUserDefaults standardUserDefaults];
        [userDefaults setObject:CityNetWorkForID forKey:@"myCityModelID"];
        [userDefaults synchronize];
        //修改
        NSArray * CityNetWorkArray = [NSArray arrayWithArray:self.arrayForCity];
        //修改
        NSUserDefaults *userDefault =[NSUserDefaults standardUserDefaults];
        [userDefault setObject:CityNetWorkArray forKey:@"myCityModel"];
        [userDefault synchronize];
        NSString *address = _addressLabel.text;
        //用空格来分割字符串
        NSArray *array = [address componentsSeparatedByString:@" "];
        provinceLabel = array[0];
        self.regionPickerView =nil;
//        [SVProgressHUD dismiss];
            dispatch_async(dispatch_get_main_queue(), ^{

        [self.regionPickerView showPickerWithProvinceName:provinceLabel cityName:nil countyName:nil index:2];
            });
        });
        NSLog(@"代码在这个线程block----%@",[NSThread currentThread]);
    }];
    NSLog(@"代码在这个线程3----%@",[NSThread currentThread]);
    
}

#define mark -这里传过去最后一个值

-(void)put{
   //    self.jumpToPhoto.userInteractionEnabled =NO;
    self.buttonforclick.selected =YES;
    self.greenValue.selected = YES;
    [SVProgressHUD shows];
    indexTag  =6;
    
    
    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"];

    
    
    
    
    
}

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


- (IBAction)didend:(UITextField *)sender {
    [self.view endEditing:YES];
}
#define mark -监听所有的texteField
- (IBAction)provinceChoose:(UITextField *)sender {

    //离线采集的所有监听
    
    
    
    
    
    
    if (sender == self.province  ) {
         [self.view endEditing:YES];
//        if ( self.IDText.text.length >0 ) {
            [self  show:sender];
            indexTag =1;
        //    self.province.userInteractionEnabled=YES;
//        }else
//        {
//            [SVProgressHUD showErrorWithStatus:@"请检查姓名和身份证"];
//            self.province.userInteractionEnabled=NO;
//        }
        
    }else if(sender == self.downTown)
    {[self.view endEditing:YES];

        [self senderSecondMessage:_provinceNumber theSecondMessage:self.province.text];
        
    }else if (sender == self.area)
    {        NSLog(@"%@",_CityNumber);
        NSLog(@"%@",self.downTown.text);
        [self.view endEditing:YES];
        [self senderCountryMessage:_CityNumber theSecondMessage:self.downTown.text];
        
        
    }else if (sender == self.village)
    {[self.view endEditing:YES];
        [self senderTownMessage:_areaNumber theSecondMessage:self.area.text];
        
    }else if (sender ==self.villageCommittee)
    {
        [self.view endEditing:YES];
        [self senderVillageMessage:_TownNumber theSecondMessage:self.village.text];
        
    }else
    {
        if (![self.Company.text isEqualToString:@""]) {
            _companyBool =YES;
        }else
        {
            _companyBool =NO;
        }
    }
    if (self.changeThreeWithUrbanAndGovern == self.button1) {
        
        if((self.province.text.length > 0) && (self.downTown.text.length > 0) && (self.area.text.length > 0) && (self.village.text.length > 0))
        {
            
            [self.view reloadInputViews];
            self.buttonforclick.backgroundColor =[UIColor colorWithRed:27/255.0 green:125/255.0 blue:206/255.0 alpha:1.0];
            self.buttonforclick.userInteractionEnabled =YES;
      
            
            [self.buttonforclick addTarget:self action:@selector(repeatVerification:) forControlEvents:UIControlEventTouchUpInside];
            
              self.greenValue.backgroundColor =[UIColor colorWithRed:25/255.0 green:149/255.0 blue:109/255.0 alpha:1.0];
            self.greenValue.userInteractionEnabled =YES;
            [self.greenValue addTarget:self action:@selector(repeatVerification:) forControlEvents:UIControlEventTouchUpInside];
        }else
        {
            [self.view reloadInputViews];
    
                self.buttonforclick.backgroundColor =[UIColor colorWithRed:191/255.0 green:191/255.0 blue:191/255.0 alpha:1.0];
         //   self.buttonforclick.userInteractionEnabled =NO;
                        self.greenValue.backgroundColor =[UIColor colorWithRed:191/255.0 green:191/255.0 blue:191/255.0 alpha:1.0];


        }
        
    }
    if ((self.changeThreeWithUrbanAndGovern == self.button2)||(self.changeThreeWithUrbanAndGovern == self.button3))
    {
        
        if((self.province.text.length > 0) && (self.downTown.text.length > 0) && (self.area.text.length > 0) &&(_companyBool == YES) )
        {
            
            [self.view reloadInputViews];
             self.buttonforclick.backgroundColor =[UIColor colorWithRed:27/255.0 green:125/255.0 blue:206/255.0 alpha:1.0];
            self.buttonforclick.userInteractionEnabled =YES;
            [self.buttonforclick addTarget:self action:@selector(repeatVerification:) forControlEvents:UIControlEventTouchUpInside];
            self.greenValue .backgroundColor =[UIColor colorWithRed:25/255.0 green:149/255.0 blue:109/255.0 alpha:1.0];
            self.greenValue.userInteractionEnabled =YES;
            [self.greenValue addTarget:self action:@selector(repeatVerification:) forControlEvents:UIControlEventTouchUpInside];
        }else
        {
            [self.view reloadInputViews];

               self.buttonforclick.backgroundColor =[UIColor colorWithRed:191/255.0 green:191/255.0 blue:191/255.0 alpha:1.0];
         //   self.buttonforclick.userInteractionEnabled =NO;
            self.greenValue.backgroundColor =[UIColor colorWithRed:191/255.0 green:191/255.0 blue:191/255.0 alpha:1.0];
 
        }
        
      }
}

- (IBAction)button_1:(UIButton *)sender {
    self.ice = 0 ;
    self.button1.selected=YES;
    self.button2.selected =NO;
    self.button3.selected =NO;
    self.villageCommittee.enabled=YES;
    self.village.enabled=YES;
    self.village.placeholder =@"";
    self.villageCommittee.placeholder =@"";
    self.companyViewHide.hidden =YES;
    if(![self.offLineGather isEqualToString:@"离线采集"]) {
//        [self shezhisuoyouweiNill];
        
    }
    self.changeThreeWithUrbanAndGovern =_button1;
    [self contraintChangeOne];
      self.companytakenToTop.constant=0;
    self.scrolWidth.constant =  self.justReadNumber -25 ;
    self.village.placeholder =@"点击按钮";
    self.villageCommittee.placeholder =@"点击按钮";
    
}
- (IBAction)button_2:(id)sender {
    self.jumpToPhoto.backgroundColor =[UIColor colorWithRed:191/255.0 green:191/255.0 blue:191/255.0 alpha:1.0];
  //  self.jumpToPhoto.userInteractionEnabled =NO;
    self.ice = 1;
    self.button1.selected =NO;
    self.button2.selected =YES;
    self.button3.selected =NO;
    self.village.selected =NO;
    //        self.village.textColor =[UIColor redColor];
    self.village.enabled=NO;
    self.village.placeholder =@"不用填写";
    [self.village setText:nil];
    self.villageCommittee.enabled=NO;
    [self.villageCommittee setText:nil];
    self.villageCommittee.placeholder =@" 不用填写";
    self.companyViewHide.hidden =NO;
   
    if(![self.offLineGather isEqualToString:@"离线采集"]) {
//        [self shezhisuoyouweiNill];
        
    }
    self.changeThreeWithUrbanAndGovern =_button2;
    [self contraintChangeTwo];
     self.companytakenToTop.constant=38;
       self.scrolWidth.constant =  self.justReadNumber - 100;
    [self geta];
    self.village.placeholder =@"点击按钮";
    self.villageCommittee.placeholder =@"点击按钮";
}

- (IBAction)button_3:(id)sender {
    self.jumpToPhoto.backgroundColor =[UIColor colorWithRed:191/255.0 green:191/255.0 blue:191/255.0 alpha:1.0];
 //  self.jumpToPhoto.userInteractionEnabled =NO;

    self.ice = 2;
    self.button1.selected =NO;
    self.button2.selected =NO;
    self.button3.selected =YES;
    self.village.selected =NO;
    //    self.village.textColor =[UIColor redColor];
    self.village.enabled=NO;
    self.village.placeholder =@" 不用填写";
    [self.village setText:nil];
    self.villageCommittee.enabled=NO;
    [self.villageCommittee setText:nil];
    self.villageCommittee.placeholder =@" 不用填写";
    self.companyViewHide.hidden =NO;
    if(![self.offLineGather isEqualToString:@"离线采集"]) {
//        [self shezhisuoyouweiNill];
    }
    self.changeThreeWithUrbanAndGovern =_button3;
    [self contraintChangeTwo];
     self.companytakenToTop.constant=38;
       self.scrolWidth.constant =  self.justReadNumber - 100;
    [self geta];
    self.village.placeholder =@"点击按钮";
    self.villageCommittee.placeholder =@"点击按钮";
}

#define mark -封装好的用来在textField前面加两个空格
-(void)textFieldAddTwoBlackPlaceinTextFiled:(UITextField *)textField
{
    UIView *blankView = [[UIView alloc] initWithFrame:CGRectMake(textField.frame.origin.x,textField.frame.origin.y,5.0, textField.frame.size.height)];
    textField.leftView = blankView;
    textField.leftViewMode =UITextFieldViewModeAlways;
}
-(BOOL)textFieldShouldReturn:(UITextField *)textField
{
     [textField resignFirstResponder];
    return YES;
}
- (IBAction)getPhotosbutton:(id)sender {


    
    
}

#pragma mark - 验证社保是否验证成功

-(void)postmessageInToPhoto:(NSMutableArray *)selfImage
{
    NSString*  path =[IPDIZHI stringByAppendingString:@"/socialsecurity/kankan/InsertInfo"];
  //2017年7月18日修改添加了手机号的输入

    
    [SVProgressHUD shows];
    [CityNetManager getSuccessSenderSocialMessageInsertInfo:path getName:self.nameText.text privateStringIdentityNumber:self.IDText.text andProvinceName:self.province.text andCityName:self.downTown.text andCountryName:self.area.text andTownName:self.village.text andvillageName:self.villageCommittee.text andTelephone:nil andCompanyName:self.Company.text andFlag:2 andVerifyType:self.ice andUimage:selfImage ocrIMage:nil ocrIMage_:nil completionHandle:^(verifyAdressModel *model, NSError *error){
         [SVProgressHUD doneShow];
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            if(model.code == 0)
            {
                dispatch_async(dispatch_get_main_queue(), ^{
                    SVProgressHUD.minimumDismissTimeInterval=1.0;
                    [SVProgressHUD showSuccessWithStatus:@"成功"];
                    NSLog(@"成功");
                });
            }else
            {
                [SVProgressHUD dismiss];
                NSLog(@"error");
            }
            
        });
    }];
}
//判断是否是数字类型
- (BOOL)isPureInt:(NSString *)string{
    NSScanner* scan = [NSScanner scannerWithString:string];
    int val;
    return [scan scanInt:&val] && [scan isAtEnd];
}

//进入摄像头的界面
-(void)enterCamera{

}
-(void)repeatVerification:(UIButton*)button
{
    
    if (self.isPhoto == NO) {
        UIAlertController *alertCon =[UIAlertController alertControllerWithTitle:@"提醒" message:@"绿色通道采集信息需要通过拍摄身份证来识别信息" preferredStyle:UIAlertControllerStyleAlert];
        [alertCon addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            [self.navigationController popViewControllerAnimated:YES];
        }]];
        [alertCon addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
            
        }]];
        
        [self presentViewController:alertCon animated:YES completion:nil];
        return;
    }

    if (self.ice > 0 && self.Company.text.length == 0 ) {
        SVProgressHUD.minimumDismissTimeInterval = 1.0;
        [SVProgressHUD showErrorWithStatus:@"请填写退休单位"];
        return;
    }
    
    
    //情况一:字符串为不为数字
    //情况二:字符串大于11
   [SVProgressHUD shows];
    if( (self.villageCommittee.text.length  == 0 || self.village.text.length ==0) &&( self.button1.selected == YES)) {
        [SVProgressHUD doneShow];
        [SVProgressHUD showErrorWithStatus:@"参保地区未填写完整"];
        return;
    }
    //离线采集的代码写在这里
    
    if ([self.offLineGather isEqualToString:@"离线采集"]) {
        
    
            dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
//                    __block UIImagePickerController *ipc = [[UIImagePickerController alloc] init];
//                    ipc.sourceType = UIImagePickerControllerSourceTypeCamera;
//                    ipc.cameraDevice=UIImagePickerControllerCameraDeviceRear;
//                    ipc.delegate = self;
//                    ipc.allowsEditing = NO;
//                    ipc.navigationBar.barTintColor =[UIColor whiteColor];
//                    ipc.navigationBar.tintColor = [UIColor whiteColor];
//                    ipc.navigationBar.titleTextAttributes = @{NSForegroundColorAttributeName:[UIColor whiteColor]};
//                    ipc.videoQuality = UIImagePickerControllerQualityType640x480;
//
//                    dispatch_async(dispatch_get_main_queue(), ^{
//                        [self presentViewController:ipc animated:YES completion:^{
//                            ipc = nil;
//                        }];
//                    });
        
        dispatch_async(dispatch_get_main_queue(), ^{
            
            

//            if ([getPeopleID getpeopleLimited] == YES) {
//                FaceStreamDetectorViewControllerW *faceVC = [[FaceStreamDetectorViewControllerW  alloc]init];
//                faceVC.faceDelegate = self;
//                //修改第一次进活体检测出现的bug
//                [self presentViewController:faceVC animated:YES completion:nil];
//      }else{
//          FaceStreamDetectorViewController *faceVC = [[FaceStreamDetectorViewController  alloc]init];
//          faceVC.faceDelegate = self;
//          //修改第一次进活体检测出现的bug
//          [self presentViewController:faceVC animated:YES completion:nil];
//
//      }
            
            
            
            
            //                          [self performSegueWithIdentifier:@"pushSegue" sender:self];
            
            
            //一整套逻辑
            LivenessViewController* dvc = [[LivenessViewController alloc] init];
            NSArray *array_ =nil;
            NSInteger kankanZhang =   [[NSUserDefaults standardUserDefaults]integerForKey:@"huoti_kankan_int"];
//            array_ =[[NSArray alloc]initWithObjects:@1, nil];
              array_ =[[NSArray alloc]initWithObjects:@1, nil];
            if (kankanZhang ==9999) {
                array_ =[[NSArray alloc]initWithObjects:@5, nil];
            }
            
            [dvc livenesswithList:array_ order:YES numberOfLiveness:1];
            __weak typeof(self) weakSelf = self;
            dvc.completion = ^(NSDictionary *images, NSMutableArray *originImage) {
                [weakSelf.imageManyImage removeAllObjects];
                
                if (originImage.count == 0) {
                    
                    
                }else{
                    [weakSelf.imageManyImage addObject:originImage[0]];
                    [weakSelf.imageManyImage addObject:originImage[originImage.count-3]];
                    [weakSelf.imageManyImage addObject:originImage[originImage.count-2]];
                    [weakSelf.imageManyImage addObject:originImage[originImage.count-1]];
                    
                    //关闭相册界面
                    
                    UIStoryboard *sb  =[UIStoryboard storyboardWithName:@"Main" bundle:nil];
                    SecondSocialViewController*bvc =[sb instantiateViewControllerWithIdentifier:@"SecondSocialViewController"];
                    bvc.baocun =self.imageManyImage;
                    bvc.social =[socialSecurityViewController sharedInstance];
                    bvc.state =NormolType;
                    if ([weakSelf.offLineGather isEqualToString:@"离线采集"]) {bvc.OffLineGather =@"离线采集"; }else{ bvc.OffLineGather =@"";}
                    bvc.greenValues =@"";
                    [self.navigationController pushViewController:bvc animated:YES];
                    
                }
                
                
                
            };
            [weakSelf presentViewController:dvc animated:YES completion:nil];
            
            
            
            
        });
                    
                    
                    [SVProgressHUD dismiss];
             
            });
        return;
                       }
    
    
    
    
    
  [CityNetManager findLibInfoIdentityNumber:[EnercryTool A:self.idText] andName:[EnercryTool A:self.nText] andProvinceName:[EnercryTool encryptUseDES:self.province.text key:DESKEY] andCityName:[EnercryTool encryptUseDES:self.downTown.text key:DESKEY]  andCountryName:[EnercryTool encryptUseDES:self.area.text key:DESKEY] andIns:self.ins andTown_name:self.village.text andVillageName:self.villageCommittee.text  andIns:self.ice  completionHandle:^(verifyAdressModel *model, NSError *error) {
       [SVProgressHUD doneShow];
      
      
      dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
          if(model.code == 0)
          {
                            dispatch_async(dispatch_get_main_queue(), ^{
              

                               
                                //修改第一次进活体检测出现的bug
                                if (button == self.greenValue) {
                                    //提醒
//                                    UIAlertController *alertCon =[UIAlertController alertControllerWithTitle:@"警告" message:@"1、照顾专用通道，非以下疾病用户严禁使用：精神疾病、偏瘫、脑瘫、治疗过程中、卧床不起、行动不变等其它重疾\n2、绿色通道的采集和认证时间，比常规方法长2-5工作日" preferredStyle:UIAlertControllerStyleAlert];
//                                    [alertCon addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
//
//                                    }]];
//                                    [alertCon addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
////
////                                        FaceStreamDetectorViewController *faceVC = [[FaceStreamDetectorViewController  alloc]init];
////                                        faceVC.faceDelegate = self;
////                                        faceVC.greenValue=@"绿色通道";
////                                        self.goGreenTongDao =YES;
////                                        [self presentViewController:faceVC animated:YES completion:nil];
//                                        
//
//                                    }]];
//
//                                    [self presentViewController:alertCon animated:YES completion:nil];
                                     [self.totalView addSubview:self.view_f];
                                    [self.totalView bringSubviewToFront:self.ViewHiden];
                                    self.goGreenTongDao = YES;
                                    self.ViewHiden.hidden = NO;

                                    
                               

                                }else if (button == self.buttonforclick){
//                                    if ([getPeopleID getpeopleLimited] == YES) {
//                                        FaceStreamDetectorViewControllerW *faceVC = [[FaceStreamDetectorViewControllerW  alloc]init];
//                                        faceVC.faceDelegate = self;
//                                        
//                                        [self presentViewController:faceVC animated:YES completion:nil];
//                                    }else{
//                                        
//                                        FaceStreamDetectorViewController *faceVC = [[FaceStreamDetectorViewController  alloc]init];
//                                        faceVC.faceDelegate = self;
//                                        
//                                        [self presentViewController:faceVC animated:YES completion:nil];
//                                    }
                                    
                                    
                                    //一整套逻辑
                                    LivenessViewController* dvc = [[LivenessViewController alloc] init];
                                    NSArray *array_ =nil;
                                    NSInteger kankanZhang =   [[NSUserDefaults standardUserDefaults]integerForKey:@"huoti_kankan_int"];
//                                    array_ =[[NSArray alloc]initWithObjects:@1, nil];
                                      array_ =[[NSArray alloc]initWithObjects:@1, nil];
                                    if (kankanZhang ==9999) {
                                        array_ =[[NSArray alloc]initWithObjects:@5, nil];
                                    }
                                    
                                    [dvc livenesswithList:array_ order:YES numberOfLiveness:1];
                                    __weak typeof(self) weakSelf = self;
                                    dvc.completion = ^(NSDictionary *images, NSMutableArray *originImage) {
                                        [weakSelf.imageManyImage removeAllObjects];
                                        
                                        if (originImage.count == 0) {
                                            
                                            
                                        }else{
                                            [weakSelf.imageManyImage addObject:originImage[0]];
                                            [weakSelf.imageManyImage addObject:originImage[originImage.count-3]];
                                            [weakSelf.imageManyImage addObject:originImage[originImage.count-2]];
                                            [weakSelf.imageManyImage addObject:originImage[originImage.count-1]];
                                            
                                            //关闭相册界面
                                            
                                            UIStoryboard *sb  =[UIStoryboard storyboardWithName:@"Main" bundle:nil];
                                            SecondSocialViewController*bvc =[sb instantiateViewControllerWithIdentifier:@"SecondSocialViewController"];
                                            bvc.baocun =self.imageManyImage;
                                            bvc.social =[socialSecurityViewController sharedInstance];
                                            bvc.state =NormolType;
                                            if ([weakSelf.offLineGather isEqualToString:@"离线采集"]) {bvc.OffLineGather =@"离线采集"; }else{ bvc.OffLineGather =@"";}
                                            bvc.greenValues =@"";
                                            [self.navigationController pushViewController:bvc animated:YES];
                                            
                                            
                                            

                                            //
                                            
                                            
                                            
                                
                                        }
                                    };
                                    [weakSelf presentViewController:dvc animated:YES completion:nil];


                                    
                                    
                                    
                                    
                                    
                                    
                                    
                                    
                                    
                                }
                             
                                //                          [self performSegueWithIdentifier:@"pushSegue" sender:self];
                            });


              

   [SVProgressHUD dismiss];
          }else{
          
          

          [SVProgressHUD dismiss];
          codeSelected *code = [codeSelected MustTakeReturn:model.code];
          [code returnCodeMethod];
          return;
          }
   });
  }];
}






- (IBAction)textFielfWithNameAndId:(UITextField *)sender {
         BOOL IDCardInjudicious = [IDCardNumber_Validate isValidateIDCardString:self.IDText.text];
    if ( self.IDText.text.length >0 && IDCardInjudicious ==YES) {
        //  self.province.userInteractionEnabled=YES;
    }else{
    SVProgressHUD.minimumDismissTimeInterval =3.0;
    [SVProgressHUD showErrorWithStatus:@"请检查姓名和身份证"];
    [self.nameText shake];
    [self.IDText shake];
 //   self.province.userInteractionEnabled=NO;
    }
    
}
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{

    
    
    
    //完成选择
    NSString *type = [info objectForKey:UIImagePickerControllerMediaType];
    //NSLog(@"type:%@",type);
    if ([type isEqualToString:@"public.image"]) {
        //转换成NSData
            __block UIImage *flippedImage = [info objectForKey:@"UIImagePickerControllerOriginalImage"];
        if (flippedImage == nil) {
            [SVProgressHUD showErrorWithStatus:@"请在设置中打开照片访问权限"];
        }
//            if (picker.cameraDevice == 1) {
                flippedImage  = [UIImage imageWithCGImage:flippedImage.CGImage
                                                    scale:1.0 orientation: UIImageOrientationLeftMirrored];
       
//            }
        //关闭相册界面
        dispatch_async(dispatch_get_main_queue(), ^{
            [picker dismissViewControllerAnimated:YES completion:^{
                
              
                if (![self.offLineGather isEqualToString:@"离线采集"] && self.goGreenTongDao == YES) {
                    //雷俊博
                    GreenChannelVC *vc = [[GreenChannelVC alloc]init];
                    vc.title = @"绿色通道";
                    vc.lastVCImage = flippedImage;
                    vc.social =[socialSecurityViewController sharedInstance];
                    vc.state = GreenCaiJi;
                    
                    [self.navigationController pushViewController:vc animated:YES];
                    
                    return ;
                }
                
                UIStoryboard *sb  =[UIStoryboard storyboardWithName:@"Main" bundle:nil];
                SecondSocialViewController*bvc =[sb instantiateViewControllerWithIdentifier:@"SecondSocialViewController"];
                bvc.image1  =flippedImage;
                bvc.social =[socialSecurityViewController sharedInstance];
                
               
   if ([self.offLineGather isEqualToString:@"离线采集"])
   {
       bvc.OffLineGather =@"离线采集";
       
   }else{
       bvc.OffLineGather =@"";
       
   }
                bvc.state =GreenCaiJi;
                if (self.goGreenTongDao == YES){
                    bvc.greenValues =@"绿色通道";
                }else{
                    bvc.greenValues =@"";
                }
                [self.navigationController pushViewController:bvc animated:YES];
     
                
                //比对
//                UIStoryboard *sb  =[UIStoryboard storyboardWithName:@"Main" bundle:nil];
//                SecondSocialViewController*bvc =[sb instantiateViewControllerWithIdentifier:@"SecondSocialViewController"];
//                bvc.baocun =self.imageManyImage;
//                bvc.social =[socialSecurityViewController sharedInstance];
//
//                if ([self.offLineGather isEqualToString:@"离线采集"]) {bvc.OffLineGather =@"离线采集"; }else{ bvc.OffLineGather =@"";}
//
//                if (self.goGreenTongDao == YES) {
//                    bvc.greenValues =@"绿色通道";
//                }else{
//                    bvc.greenValues =@"";
//                }
//
//                [self.navigationController pushViewController:bvc animated:YES];
                
                
                
                
                
                
                
                
                
                
                
                
                
                
                
                
                
        

            }];
        });
    }
}
-(void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
    [picker dismissViewControllerAnimated:YES completion:^{
    }];
}
//ocr
#pragma mark 验证证件OCR
- (IBAction)explainIdentifly:(id)sender {
    SCCaptureCameraController *con = [[SCCaptureCameraController alloc] init];
    con.scNaigationDelegate = self;
    con.iCardType = TIDCARD2;
    con.isDisPlayTxt = YES;
    //con.TimeKey = TimeKeyS;
    con.ScanMode = TIDC_SCAN_MODE;
   // self.province.userInteractionEnabled =YES;
    [self presentViewController:con animated:YES completion:NULL];
    
}
-(void)getOCR
{
#if TARGET_IPHONE_SIMULATOR
    
#else
    // Do any additional setup after loading the view, typically from a nib.
    // 如果是客户使用自己的界面，调用识别引擎参考代码如下
    
    // 打开引擎
    Gint ret = 0;
    Gint vaule = 1;
    ret = TREC_StartUP(TREC_GetEngineTimeKEY());
    if (ret == 100) {
        NSLog(@"引擎过期\n");
        return;
    }
    if (ret == 100) {
        NSLog(@"引擎过期\n");
        return;
    }if (ret == 101) {
        NSLog(@"引擎绑定失败\n");
        return;
    }
    //获取引擎信息，可以不用操作，可有可无
    //  self.nameText.text=  [[NSString alloc] initWithString:[NSString stringWithFormat:@"%@\n%@\n%@\n",TREC_GetCopyrightInfoArray(),TREC_GetVersionArray(),TREC_GetTimeStatus()]];
    // 设置引擎参数
    ret = TREC_SetParam(T_SET_HEADIMG, &vaule);
    // 设置引擎类型
    ret = TREC_SetSupportEngine(TIDCARD2);// 演示使用身份证，其他证件以此类推
    if (ret != 1) {
        NSLog(@"引擎不支持\n");
        TREC_ClearUP();
        return;
    }
    
    
    // 引擎内存释放
    ret = TREC_ClearUP();
#endif
    
    
    
}
- (void)sendIDCValue:(NSString *)name SEX:(NSString *)sex FOLK:(NSString *)folk BIRTHDAY:(NSString *)birthday ADDRESS:(NSString *) address NUM:(NSString *)num
{
    NSLog(@"idc  = %@\n%@\n%@\n%@\n%@\n%@\n",name,sex,folk,birthday,address,num);
    self.nameText.text =name;
    
    self.IDText.text=num;

       // self.province.userInteractionEnabled=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) {
        NSLog(@"headiamge = %@\n",image);
//        NSData *smallImgData = UIImageJPEGRepresentation(image, 0.2);
        NSData *smallImgData =UIImagePNGRepresentation(image);
        self.ocrBase64_ = [smallImgData 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 *smallImgData =UIImageJPEGRepresentation(cardImage, 0.2);
        NSData *smallImgData =UIImageJPEGRepresentation([self imageByScalingAndCroppingForSize:CGSizeMake(667, 375) and:cardImage], 1.0);
    self.ocrBase64 = [smallImgData base64EncodedStringWithOptions:0];
     
    
    
}
- (void)sendIDCARDBackAction
{
    
}
+ (socialSecurityViewController *)sharedInstance{
    static socialSecurityViewController *p = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        
        UIStoryboard *sb  =[UIStoryboard storyboardWithName:@"Main" bundle:nil];
        p=[sb instantiateViewControllerWithIdentifier:@"socialSecurityViewController"];
    });
    return p;
}
- (UIImage*)imageByScalingAndCroppingForSize:(CGSize)targetSize and:(UIImage*)imageKs
{
    UIImage *sourceImage = imageKs;
    UIImage *newImage = nil;
    CGSize imageSize = sourceImage.size;
    CGFloat width = imageSize.width;
    CGFloat height = imageSize.height;
    CGFloat targetWidth = targetSize.width;
    CGFloat targetHeight = targetSize.height;
    CGFloat scaleFactor = 0.0;
    CGFloat scaledWidth = targetWidth;
    CGFloat scaledHeight = targetHeight;
    CGPoint thumbnailPoint = CGPointMake(0.0,0.0);
    
    if (CGSizeEqualToSize(imageSize, targetSize) == NO)
    {
        CGFloat widthFactor = targetWidth / width;
        CGFloat heightFactor = targetHeight / height;
        
        if (widthFactor > heightFactor)
            scaleFactor = widthFactor; // scale to fit height
        else
            scaleFactor = heightFactor; // scale to fit width
        scaledWidth= width * scaleFactor;
        scaledHeight = height * scaleFactor;
        
        // center the image
        if (widthFactor > heightFactor)
        {
            thumbnailPoint.y = (targetHeight - scaledHeight) * 0.5;
        }
        else if (widthFactor < heightFactor)
        {
            thumbnailPoint.x = (targetWidth - scaledWidth) * 0.5;
        }
    }
    
    UIGraphicsBeginImageContext(targetSize); // this will crop
    
    CGRect thumbnailRect = CGRectZero;
    thumbnailRect.origin = thumbnailPoint;
    thumbnailRect.size.width= scaledWidth;
    thumbnailRect.size.height = scaledHeight;
    
    [sourceImage drawInRect:thumbnailRect];
    
    newImage = UIGraphicsGetImageFromCurrentImageContext();
    if(newImage == nil)
        NSLog(@"could not scale image");
    
    //pop the context to get back to the default
    UIGraphicsEndImageContext();
    return newImage;
}
-(void)geta{
    if((self.province.text.length > 0) && (self.downTown.text.length > 0) && (self.area.text.length > 0) &&(_companyBool == YES))
    {
        
        [self.view reloadInputViews];
        self.jumpToPhoto .backgroundColor =[UIColor colorWithRed:25/255.0 green:149/255.0 blue:109/255.0 alpha:1.0];
        self.jumpToPhoto.userInteractionEnabled =YES;
        
        
        
        
    }else
    {
        [self.view reloadInputViews];
        self.jumpToPhoto.backgroundColor =[UIColor colorWithRed:191/255.0 green:191/255.0 blue:191/255.0 alpha:1.0];
    //    self.jumpToPhoto.userInteractionEnabled =NO;
    }
    
    
    
}
//-(void)sendW:(FaceStreamDetectorViewControllerW *)bvc nextputImageNSarray:(NSMutableArray *)arrayFrameWork{
//    [self.imageManyImage removeAllObjects];
//
//    if (arrayFrameWork.count == 0) {
//
//
//    }else{
//        [self.imageManyImage addObject:arrayFrameWork[0]];
//        [self.imageManyImage addObject:arrayFrameWork[1]];
//        [self.imageManyImage addObject:arrayFrameWork[2]];
//        [self.imageManyImage addObject:arrayFrameWork[3]];
//
//
//
//
//
//        //关闭相册界面
//
//        UIStoryboard *sb  =[UIStoryboard storyboardWithName:@"Main" bundle:nil];
//        SecondSocialViewController*bvc =[sb instantiateViewControllerWithIdentifier:@"SecondSocialViewController"];
//        bvc.baocun =self.imageManyImage;
//        bvc.social =[socialSecurityViewController sharedInstance];
//        bvc.state =NormolType;
//        if ([self.offLineGather isEqualToString:@"离线采集"]) {bvc.OffLineGather =@"离线采集"; }else{ bvc.OffLineGather =@"";}
//        bvc.greenValues =@"";
//        [self.navigationController pushViewController:bvc animated:YES];
//
//
//
//
//
//
//
//
//
//
//
//    }
//}
//
//
//-(void)send:(FaceStreamDetectorViewController *)bvc nextputImageNSarray:(NSMutableArray *)arrayFrameWork
//{
//    [self.imageManyImage removeAllObjects];
//
//    if (arrayFrameWork.count == 0) {
//
//
//    }else{
//        [self.imageManyImage addObject:arrayFrameWork[0]];
//        [self.imageManyImage addObject:arrayFrameWork[1]];
//        [self.imageManyImage addObject:arrayFrameWork[2]];
//        [self.imageManyImage addObject:arrayFrameWork[3]];
//
//
//
//
//
//        //关闭相册界面
//
//                UIStoryboard *sb  =[UIStoryboard storyboardWithName:@"Main" bundle:nil];
//                SecondSocialViewController*bvc =[sb instantiateViewControllerWithIdentifier:@"SecondSocialViewController"];
//            bvc.baocun =self.imageManyImage;
//                bvc.social =[socialSecurityViewController sharedInstance];
//                  bvc.state =NormolType;
//                if ([self.offLineGather isEqualToString:@"离线采集"]) {bvc.OffLineGather =@"离线采集"; }else{ bvc.OffLineGather =@"";}
//            bvc.greenValues =@"";
//                [self.navigationController pushViewController:bvc animated:YES];
//
//
//
//
//
//
//
//
//
//
//
//    }
//}


-(NSMutableArray *)imageManyImage
{
    if (!_imageManyImage) {
        _imageManyImage =[NSMutableArray array];
    }
    return _imageManyImage;
    
}

- (IBAction)buttTag:(UIButton *)sender {
    //  返回
    //7913   继续
    switch (sender.tag) {
        case 7912:
            // 返回
            self.ViewHiden.hidden = YES;
            [self.view_f removeFromSuperview];
            break;
        case 7913:
            // //继续
            [self jixu];
            break;
        default:
            break;
    
    
    
}
}

#pragma mark - 绿色通道
-(void)jixu{
    
    
    
       // [self baidu];
    self.goGreenTongDao =YES;
    self.ViewHiden.hidden = YES;
    [self.view_f removeFromSuperview];
    
    
    
    __block UIImagePickerController *ipc = [[UIImagePickerController alloc] init];
    ipc.sourceType = UIImagePickerControllerSourceTypeCamera;
    ipc.cameraDevice=UIImagePickerControllerCameraDeviceRear;
    ipc.delegate = self;
    ipc.allowsEditing = NO;
    ipc.navigationBar.barTintColor =[UIColor whiteColor];
    ipc.navigationBar.tintColor = [UIColor whiteColor];
    ipc.navigationBar.titleTextAttributes = @{NSForegroundColorAttributeName:[UIColor whiteColor]};
    ipc.videoQuality = UIImagePickerControllerQualityType640x480;
    dispatch_async(dispatch_get_main_queue(), ^{
        [self presentViewController:ipc animated:YES completion:^{
            ipc = nil;
        }];
    });


        
        
        
    }
-(void)camerma{
    
    __block UIImagePickerController *ipc = [[UIImagePickerController alloc] init];
    ipc.sourceType = UIImagePickerControllerSourceTypeCamera;
    ipc.cameraDevice=UIImagePickerControllerCameraDeviceRear;
    ipc.delegate = self;
    ipc.allowsEditing = NO;
    ipc.navigationBar.barTintColor =[UIColor whiteColor];
    ipc.navigationBar.tintColor = [UIColor whiteColor];
    ipc.navigationBar.titleTextAttributes = @{NSForegroundColorAttributeName:[UIColor whiteColor]};
    ipc.videoQuality = UIImagePickerControllerQualityType640x480;
    
    dispatch_async(dispatch_get_main_queue(), ^{
        [self presentViewController:ipc animated:YES completion:^{
            ipc = nil;
        }];
    });
    
}

#pragma mark - 取照片逻辑
-(void)baidu{
    DetectionViewController* dvc = [[DetectionViewController alloc] init];
    __weak typeof(self) weakSelf = self;
    dvc.completion = ^(NSDictionary *images, NSMutableArray *originImage) {
        [weakSelf.imageManyImage removeAllObjects];
        if (originImage.count == 0) {
            [SVProgressHUD showErrorWithStatus:@"请保持人脸姿态"];
        }else{
            
            UIStoryboard *sb  =[UIStoryboard storyboardWithName:@"Main" bundle:nil];
            SecondSocialViewController*bvc =[sb instantiateViewControllerWithIdentifier:@"SecondSocialViewController"];
            bvc.image1  =originImage[originImage.count-1];
            bvc.social =[socialSecurityViewController sharedInstance];
            if ([self.offLineGather isEqualToString:@"离线采集"]) {bvc.OffLineGather =@"离线采集"; }else{ bvc.OffLineGather =@"";}
            bvc.state =GreenCaiJi;
            if (self.goGreenTongDao == YES) {
                bvc.greenValues =@"绿色通道";
            }else{
                bvc.greenValues =@"";
            }
            [self.navigationController pushViewController:bvc animated:YES];
        }
        //finish
        
    };
    UINavigationController *navi = [[UINavigationController alloc] initWithRootViewController:dvc];
    navi.navigationBarHidden = true;
    [self presentViewController:navi animated:YES completion:nil];
    
    
    
}



@end
