//
//  MyPickerViewController.m
//  Open
//
//  Created by gao on 2016/11/9.
//  Copyright © 2016年 黄江涛 . All rights reserved.
//

#import "MyPickerViewController.h"
#import "ShowPicker.h"
#import "successViewController.h"

#import "CLMarkButton.h"
//#import "FaceStreamDetectorViewController.h"
#import "artificalViewController.h"
#import <MBProgressHUD.h>
#import "MBProgressHUD+NJ.h"
#import "KKUserIdentifyViewController.h"
#import "FaceImageModel.h"

@interface MyPickerViewController ()<passImagesDelegate>
{
    NSArray *array;

}
@property (weak, nonatomic) IBOutlet UIImageView *ImageViews2;

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

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

@property (weak, nonatomic) IBOutlet UIImageView *imageView4;
@property (weak, nonatomic) IBOutlet UIView *backguardView;

//失败的照片
@property(nonatomic,strong)UIImageView *failurePic;


//四个按钮选取
@property (weak, nonatomic) IBOutlet  CLMarkButton *buttonControl1;

@property (weak, nonatomic) IBOutlet CLMarkButton *buttonControl2;

@property (weak, nonatomic) IBOutlet CLMarkButton *buttonControl3;

@property (weak, nonatomic) IBOutlet CLMarkButton *buttonControl4;

@property(nonatomic,strong)	 CLMarkButton *changeButton5;

@property (weak, nonatomic) IBOutlet UIButton *buttonForCameraPost;
//照片选择按钮
@property(nonatomic)	 NSInteger pictureChoose;
@property (weak, nonatomic) IBOutlet UIButton *buttonForReChoose;
//得到传过去的图片
@property(nonatomic,strong)UIImage *image_1;
@property(nonatomic,strong)UIImage *image_2;

//拿到四个image的宽160
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *iHeight_1;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *iHeight_2;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *iHeight_3;

@property (weak, nonatomic) IBOutlet NSLayoutConstraint *iHeight_4;
@property(nonatomic,strong)NSMutableArray *dataArr;

@property(nonatomic,strong)NSString *documentsPath_3;
//选择照片认证图片你的高度40
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *SmallselectPhoto;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *button_2_Top_height;

@property (weak, nonatomic) IBOutlet NSLayoutConstraint *button_1_top_height;
@property(nonatomic,strong)NSMutableArray *baocun;
@end
//san个jing'nang	    
@implementation MyPickerViewController
-(NSMutableArray *)dataArr{
    if (_dataArr) {
        _dataArr =[NSMutableArray new];
    }
    return _dataArr;
}
-(NSMutableArray *)baocun
{
    if (!_baocun) {
        _baocun =[NSMutableArray  new];
    }
    return _baocun;
}
-(NSString *)documentsPath_3{
    if (!_documentsPath_3) {
        //        _documentsPath_3=NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES)[0];
        _documentsPath_3 =NSSearchPathForDirectoriesInDomains(NSCachesDirectory,NSUserDomainMask,YES)[0];
    }
    return _documentsPath_3;
}
-(NSMutableArray *)arrayImages
{
    if (!_arrayImages) {
       _arrayImages =[NSMutableArray array];
    }
    return _arrayImages;
}
-(NSMutableArray *)array_FixBug{
    if (!_array_FixBug) {
        _array_FixBug =[NSMutableArray array];
    }
    return _array_FixBug;
}





- (instancetype)init {
    if (self = [super init]) {
        //
        NSLog(@"1");
    }
    return self;
}

- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    if (self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]) {
        //
        NSLog(@"2");
    }
    return self;
}
- (id)initWithCoder:(NSCoder *)aDecoder {
//    [self viewDidLoad];
    if (self = [super initWithCoder:aDecoder]) {
  
    }
    return self;
}
- (void)awakeFromNib {
    [super awakeFromNib];
    NSLog(@"4");
}

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:YES];
    
    self.changeButton5 =self.buttonControl4;
    [[NSUserDefaults standardUserDefaults ]setInteger:1 forKey:@"huoti_kankan_int"];
    [[NSUserDefaults standardUserDefaults]synchronize];
}
    WEBS
-(void)buttonClick_1{    ZHINENGKEFU}
-(void)viewDidLoad
{

        [super viewDidLoad];
    //改支付
  //  self.shareHide.hidden = YES;

    
    
    if([[UIScreen mainScreen]bounds].size.height == 480) {self.SmallselectPhoto.constant = 0;
    self.button_1_top_height.constant =17;
    self.button_2_Top_height.constant =17;
    }else{
        self.SmallselectPhoto.constant = 40;self.button_1_top_height.constant =0; self.button_2_Top_height.constant =0;
    }
    
    
    
//    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.view reloadInputViews];
    if (self.ImageViews.image == nil) {

      
//        if([[UIScreen mainScreen]bounds].size.height == 568)
//        {
//  // 5s
//            self.iHeight_1.constant = 145;
//            self.iHeight_2.constant = 145;
//            self.iHeight_3.constant = 145;
//            self.iHeight_4.constant = 145;
//            
//        }else if([[UIScreen mainScreen]bounds].size.height == 736){
//        //7s
//            self.iHeight_1.constant = 204.6;
//            self.iHeight_2.constant = 204.6;
//            self.iHeight_3.constant = 204.6;
//            self.iHeight_4.constant = 204.6;
//            
//            
//        }
        self.ImageViews.image = self.arrayImages[0];
         self.imageView4.image = self.arrayImages[1];
         self.imageView3.image = self.arrayImages[2];
        self.ImageViews2.image = self.arrayImages[3];
        
        //修改了fix_bug
     
        if (self.arrayImages.count >0 ) {
               [self.array_FixBug addObjectsFromArray:self.arrayImages];
        }
        
        


//        [self.arrayImages removeAllObjects];
    }
        self.buttonForCameraPost.layer.cornerRadius = 5;
        self.buttonForReChoose.layer.cornerRadius=5;
        
        
        
        self.backguardView.hidden =YES;
        
        self.buttonForCameraPost.userInteractionEnabled =YES;
        
        [self selectPicToChangeImageView];
    //你需要做一些调用苹果内部付款的操作
 
    [self senderMethod:self.modelCode];
   
}

#pragma mark - passImagesDelegate
- (void)passImages:(NSArray *)imagesArray {
    
    
    
    //[SVProgressHUD showSuccessWithStatus:@"人脸识别成功"];
    
    
//    NSArray*newImageArray = [imagesArray sortedArrayUsingComparator:^NSComparisonResult(id  _Nonnull obj1, id  _Nonnull obj2) {
//         FaceImageModel *model1 = (FaceImageModel *)obj1;
//        FaceImageModel *model2 = (FaceImageModel *)obj2;
//         // 因为不满足sortedArrayUsingComparator方法的默认排序顺序，则需要交换
//         if (model1.score < model2.score) return NSOrderedDescending;
//         return NSOrderedAscending;
//     }];

     NSMutableArray *originImage = [[NSMutableArray alloc]init];
     //NSMutableArray *scoreArray = [[NSMutableArray alloc]init];
     for (int i = 0; i < imagesArray.count; i++) {



         FaceImageModel*imageModel = imagesArray[i];
         [originImage addObject:imageModel.image];
        

     }
    
    
    [self.view reloadInputViews];
    //// self.ImageViews.image =   [UIImage imageWithCGImage:(__bridge CGImageRef _Nonnull)(images1) scale:1 orientation:UIImageOrientationLeftMirrored];
    //    self.ImageViews.tag =1001;
    //    //   /.jpeg这个方法可以通过后面的参数来设置图片的大小
    if (originImage.count == 0) {
        //先判断有没有值
        if (self.array_FixBug.count >0) {
            //判断是什么类型的字符串
            for (id obj in self.array_FixBug)
            {
                if([obj isKindOfClass:[UIImage class]])
                {
                    self.ImageViews.image =self.array_FixBug[0];
                    self.ImageViews2.image =self.array_FixBug[1];
                    self.imageView3.image =self.array_FixBug[2];
                    self.imageView4.image =self.array_FixBug[3];
                }
            }
        }
    }else{
        self.ImageViews.image =[originImage copy][0];
        self.ImageViews2.image =[originImage copy][originImage.count-3];
        //    self.ImageViews2.tag =1002;
        self.imageView3.image =[originImage copy][originImage.count-2];
        self.imageView4.image =[originImage copy][originImage.count-1];
    }

    //    self.imageView4.tag =1004;
}

- (void)passFail {
    [SVProgressHUD showErrorWithStatus:@"人脸识别失败"];
}



#define mark 多张照片上传认证

//我改动的地方
-(void)senderManyPic{
    
    
    [self.baocun removeAllObjects];
    

    
    [self.baocun addObject:[self imageChangeType:self.ImageViews2.image]];
    [self.baocun addObject:[self imageChangeType:self.imageView3.image]];
    [self.baocun addObject:[self imageChangeType:self.imageView4.image]];
//    [CityNetManager manyPic:self.baocun completionHandle:^(verifyAdressModel *model, NSError *error) {
//
//        if (error) {
//            return;
//        }
//
//        if (model.code == 0) {
//            //成功
//            [SVProgressHUD showSuccessWithStatus:@"测试上传成功"];
//        }
//
//
//
//    }];
    
}


-(void)postmessageInToPhoto:(UIImage *)selfImage
{
    
//    [self senderManyPic];

    
    
    
    self.buttonForCameraPost.userInteractionEnabled =NO;
    self.image_1 =selfImage;
    selfImage=  [JobUtil imagehuangzhuan:selfImage rotation:UIImageOrientationLeft];

    NSUserDefaults* userDefault=[NSUserDefaults standardUserDefaults];
    NSString *names =[userDefault objectForKey:@"name"];
    NSString *identifity =[userDefault objectForKey:@"identityNumber"];
    NSString *ID =[userDefault objectForKey:@"bak"];
    NSLog(@"ID:%@",ID);
    NSString *path =@"";
 
    if([self.greenValues isEqualToString:@"绿色通道"]){
           path =[IPDIZHI stringByAppendingString:@"/socialsecurity/kankan/greenChannelVerify"];
    }else{
         path =[IPDIZHI stringByAppendingString:@"/socialsecurity/kankan/verifyPhoto"];
    }
    
    
    
    
    UIImage *  flippedImage= selfImage;
//这里做了修改2017年6月27日
  flippedImage  = [UIImage imageWithCGImage:flippedImage.CGImage
                                              scale:1.0 orientation: UIImageOrientationUpMirrored];
//2017年6月27日
    //2017年7月17日 (483,664)  -->  (360,270)
  flippedImage=  [self imageByScalingAndCroppingForSize:CGSizeMake(360, 270) and:flippedImage];


     NSData  *dateImage1 =UIImageJPEGRepresentation( flippedImage,0.86);
 


//test---------------------------------------------------------------------------------------------------------------------------------------------------
    UIImage *one_two = [UIImage imageWithData:dateImage1];
   NSString *targetPath_3333=[self.documentsPath_3 stringByAppendingPathComponent:@"1123123123认证照片.jpg"];
    [UIImagePNGRepresentation(one_two) writeToFile:targetPath_3333 atomically:YES];
//test------------------------------------------------------------------------------------------------------------------------------------------------------

 [SVProgressHUD shows];

    [self.baocun removeAllObjects];

    NSArray *dataArray =@[ [self imageChangeType:selfImage],
                          [self imageChangeType:self.ImageViews2.image],
                          [self imageChangeType:self.imageView3.image],
                          [self imageChangeType:self.imageView4.image]];
//        self.baocun removeObject: = [self.baocun valueForKeyPath:@"@distinctUnionOfObjects.self"];
    
    
    for (NSString *str in dataArray) {
        if (![self.baocun containsObject:str]) {
            [self.baocun addObject:str];
        }else{
            if ([self.baocun containsObject:str]) {
                [self.baocun removeObject:str];
                continue;
            }
        }
    }
    

[CityNetManager  getaddressPhotoToThePath:path getID:ID FortheName:names theIdentityNumberPara:identifity image:dateImage1 andPhone:self.telPhone andArray:self.baocun  completionHandle:^(verifyAdressModel *model, NSError *error) {
    [SVProgressHUD doneShow];
     dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{

         
    if(model.code == 0)
    {
        
//        [self  senderManyPic];
        
        
        
        dispatch_async(dispatch_get_main_queue(), ^{
                self.buttonForCameraPost.userInteractionEnabled =YES;
        [SVProgressHUD dismiss];
            if (model.RESULT) {
                
//                NSURL *url = [NSURL URLWithString: model.RESULT];
//                NSData *data = [NSData dataWithContentsOfURL: url];
//                UIImage *image = [UIImage imageWithData: data];
                NSData *dataBase64 =[[NSData alloc]initWithBase64EncodedString:model.RESULT options:0];
                UIImage *image = [UIImage imageWithData:dataBase64];
                self.image_2 =image;
            }
        [self performSegueWithIdentifier:@"successSegue" sender:self];
      });
//        dispatch_async(dispatch_get_main_queue(), ^{
//            self.view_f.hidden = NO;
//         //   self.shareHide.hidden = NO;
//
//        });
        
    }
    else if(model.code == 1007)
    {
        dispatch_async(dispatch_get_main_queue(), ^{
                self.buttonForCameraPost.userInteractionEnabled =YES;
        [SVProgressHUD dismiss];
        [self faceToAN];
        self.backguardView.hidden=NO;
         });
    }else if(model.code == 1012)
    { dispatch_async(dispatch_get_main_queue(), ^{
       self.buttonForCameraPost.userInteractionEnabled =YES;
        [SVProgressHUD dismiss];
        [self faceToAN];
        self.backguardView.hidden=NO;
         });
    }else if(model.code == 4)
    {dispatch_async(dispatch_get_main_queue(), ^{
            self.buttonForCameraPost.userInteractionEnabled =YES;
         [SVProgressHUD dismiss];
        [self faceToAN];
        self.backguardView.hidden=NO;
       
           });
    }else if(model.code == 28){
    
        dispatch_async(dispatch_get_main_queue(), ^{
            self.buttonForCameraPost.userInteractionEnabled =YES;
            //[SVProgressHUD showErrorWithStatus:@"信息正在审核中,请耐心等待"];
            //[self performSegueWithIdentifier:@"unwindB" sender:self];
            UIAlertController *alertCon =[UIAlertController alertControllerWithTitle:@"信息正在审核中,请耐心等待!" message:nil preferredStyle:UIAlertControllerStyleAlert];
            [alertCon addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                NSLog(@"%@",@"确定了!!!!!");
                for (UIViewController*vc in self.navigationController.viewControllers) {
                    if ([vc isKindOfClass:[KKUserIdentifyViewController class]]) {
                        KKUserIdentifyViewController*currentVC  = (KKUserIdentifyViewController *)vc;
                        [currentVC clearText];
                        [self.navigationController popToViewController:currentVC animated:YES];
                        break;
                    }
                }
             self.navigationController.navigationBar.translucent = YES;
                    [self.navigationController.navigationBar setBarTintColor:[UIColor colorWithRed:27/255.0 green:132/255.0 blue:208/255.0 alpha:1.0]];
                if ([UIScreen mainScreen].bounds.size.height == 480) {
                    [self.navigationController setNavigationBarHidden:NO animated:YES];
                }
            }]];
            [self presentViewController:alertCon animated:YES completion:nil];
        });

    }else if(model.code == 1015)
        {
            dispatch_async(dispatch_get_main_queue(), ^{
                  self.buttonForCameraPost.userInteractionEnabled =YES;
                [SVProgressHUD showErrorWithStatus:@"您人脸数据未采集,请联系所在地社保部门"];
                
            });
    
        }else if(model.code == 42){
            dispatch_async(dispatch_get_main_queue(), ^{
              self.buttonForCameraPost.userInteractionEnabled =YES;
                [self.navigationController popViewControllerAnimated:YES];
   });
    }else
    {
        dispatch_async(dispatch_get_main_queue(), ^{
                self.buttonForCameraPost.userInteractionEnabled =YES;
            [self faceToAN];
            self.backguardView.hidden=NO;
            [SVProgressHUD dismiss];
        });

    }
         //
         [SVProgressHUD dismiss];
         codeSelected *code = [codeSelected MustTakeReturn:model.code];
         [code returnCodeMethod];
       
         
         
         
         
         
         if (model.code != 0) {
             dispatch_async(dispatch_get_main_queue(), ^{
                 self.buttonForCameraPost.userInteractionEnabled =YES;
                 self.failurePic =[[UIImageView alloc]init];
                 self.failurePic.image =selfImage;
             });
             
         }

});

   
}];
   
    
}
-(void)senderMethod:(NSInteger)model{
    
    [SVProgressHUD dismiss];
    if(model == 1007)
    {
        dispatch_async(dispatch_get_main_queue(), ^{
            [self faceToAN];
            self.backguardView.hidden=NO;
        });
    }else if(model == 1012)
    { dispatch_async(dispatch_get_main_queue(), ^{
        [self faceToAN];
        self.backguardView.hidden=NO;
    });
    }else if(model == 4)
    {dispatch_async(dispatch_get_main_queue(), ^{
        [self faceToAN];
        self.backguardView.hidden=NO;
        
    });
    }else if(model == 28){
        
        dispatch_async(dispatch_get_main_queue(), ^{
            //[SVProgressHUD showErrorWithStatus:@"信息正在审核中,请耐心等待"];
            UIAlertController *alertCon =[UIAlertController alertControllerWithTitle:@"信息正在审核中,请耐心等待!" message:nil preferredStyle:UIAlertControllerStyleAlert];
            [alertCon addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                NSLog(@"%@",@"确定了!!!!!");
                for (UIViewController*vc in self.navigationController.viewControllers) {
                    if ([vc isKindOfClass:[KKUserIdentifyViewController class]]) {
                        KKUserIdentifyViewController*currentVC  = (KKUserIdentifyViewController *)vc;
                        [currentVC clearText];
                        [self.navigationController popToViewController:currentVC animated:YES];
                        break;
                    }
                }
             self.navigationController.navigationBar.translucent = YES;
                    [self.navigationController.navigationBar setBarTintColor:[UIColor colorWithRed:27/255.0 green:132/255.0 blue:208/255.0 alpha:1.0]];
                if ([UIScreen mainScreen].bounds.size.height == 480) {
                    [self.navigationController setNavigationBarHidden:NO animated:YES];
                }
            }]];
            [self presentViewController:alertCon animated:YES completion:nil];
            //[MBProgressHUD showError:@"信息正在审核中,请耐心等待"];
            
            //[self performSegueWithIdentifier:@"unwindB" sender:self];
            return ;
        });
        
    }else if(model == 1015)
    {
        dispatch_async(dispatch_get_main_queue(), ^{
//            [SVProgressHUD showErrorWithStatus:@"您人脸数据未采集,请联系所在地社保部门"];
            
            [MBProgressHUD showError:@"您人脸数据未采集,请联系所在地社保部门"];
            return ;
            
        });
        
    }else if(model == 42){
        dispatch_async(dispatch_get_main_queue(), ^{
            [self.navigationController popViewControllerAnimated:YES];
        });
        
    }else
    {
        dispatch_async(dispatch_get_main_queue(), ^{
            [self faceToAN];
            self.backguardView.hidden=NO;
        });
        
    }
    //
    codeSelected *code = [codeSelected MustTakeReturn:model];
    [code returnCodeMethod2];
    
}

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    if ([segue.identifier isEqualToString:@"successSegue"])  {
 
        successViewController *blueVC = segue.destinationViewController;
        blueVC.imageView1 =self.image_1;
        blueVC.imageView2 =self.image_2;
        blueVC.province =self.province;
        blueVC.city =self.city;
        blueVC.county =self.county;
    }
}
//保存照片转换逻辑
//我改动的地方
-(NSString*)imageChangeType:(UIImage*)selfImage{
    UIImage *  flippedImage= selfImage;
    //这里做了修改2017年6月27日
    flippedImage  = [UIImage imageWithCGImage:flippedImage.CGImage
                                        scale:1.0 orientation: UIImageOrientationUpMirrored];
    //2017年6月27日
    //2017年7月17日 (483,664)  -->  (360,270)
    flippedImage=  [self imageByScalingAndCroppingForSize:CGSizeMake(360, 270) and:flippedImage];
    NSData  *dateImage1 =UIImageJPEGRepresentation( flippedImage,0.86);
    
    //2017年7月17日放入测试的bug
    //test---------------------------------------------------------------------------------------------------------------------------------------------------
    UIImage *one_two = [UIImage imageWithData:dateImage1];
    NSString *targetPath_3333=[self.documentsPath_3 stringByAppendingPathComponent:@"社保采集的图片.jpg"];
    [UIImagePNGRepresentation(one_two) writeToFile:targetPath_3333 atomically:YES];
    //test------------------------------------------------------------------------------------------------------------------------------------------------------
    //
    //   NSData  *dateImage1 = UIImagePNGRepresentation(selfImage);
    
    NSString *str3=[EnercryTool encryptBase64:dateImage1];
    return str3;
    
}


//人脸动画
-(void)faceToAN
{
    CATransition *applicationLoadViewIn =[CATransition animation];
    [applicationLoadViewIn setDuration:0.5];
    [applicationLoadViewIn setType:kCATransitionReveal];
    [applicationLoadViewIn setTimingFunction:[CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseIn]];
    //you view need to replace
    [[self.backguardView layer]addAnimation:applicationLoadViewIn forKey:kCATransitionReveal];
  
    [self.backguardView reloadInputViews];
    [self.view reloadInputViews];
    self.backguardView.hidden=NO;
    
}


-(void)KZViewControllerEnter
{
//    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  //  dispatch_async(dispatch_get_main_queue(), ^{
//        FaceStreamDetectorViewController *faceVC = [[FaceStreamDetectorViewController  alloc]init];
//        faceVC.faceDelegate = self;
//        if([self.greenValues isEqualToString:@"绿色通道"]){
//            faceVC.greenValue = @"绿色通道";
//        }
//        [self presentViewController:faceVC animated:YES completion:nil];
//
//
        
        //老版本的活体检测
//        if ([getPeopleID getpeopleLimited] == YES) {
//            FaceStreamDetectorViewControllerW *faceVC = [[FaceStreamDetectorViewControllerW  alloc]init];
//            faceVC.faceDelegate = self;
//            if([self.greenValues isEqualToString:@"绿色通道"]){
//                faceVC.greenValue = @"绿色通道";
//            }
//            [self presentViewController:faceVC animated:YES completion:nil];
//        }else{
//            FaceStreamDetectorViewController *faceVC = [[FaceStreamDetectorViewController  alloc]init];
//            faceVC.faceDelegate = self;
//            if([self.greenValues isEqualToString:@"绿色通道"]){
//                faceVC.greenValue = @"绿色通道";
//            } //            [self presentViewController:faceVC animated:YES completion:nil];
//
//        }
        
        
        //一整套逻辑
        LivenessViewController* dvc = [[LivenessViewController alloc] init];
        dvc.delegate = self;
        NSArray *array_ =nil;
        NSInteger kankanZhang =   [[NSUserDefaults standardUserDefaults]integerForKey:@"huoti_kankan_int"]; //相当于安卓Sharedpreferences
    
//        array_ =[[NSArray alloc]initWithObjects:@1,@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.view reloadInputViews];
            //// self.ImageViews.image =   [UIImage imageWithCGImage:(__bridge CGImageRef _Nonnull)(images1) scale:1 orientation:UIImageOrientationLeftMirrored];
            //    self.ImageViews.tag =1001;
            //    //   /.jpeg这个方法可以通过后面的参数来设置图片的大小
            if (originImage.count == 0) {
                //先判断有没有值
                if (weakSelf.array_FixBug.count >0) {
                    //判断是什么类型的字符串
                    for (id obj in weakSelf.array_FixBug)
                    {
                        if([obj isKindOfClass:[UIImage class]])
                        {
                            weakSelf.ImageViews.image =weakSelf.array_FixBug[0];
                            weakSelf.ImageViews2.image =weakSelf.array_FixBug[1];
                            weakSelf.imageView3.image =weakSelf.array_FixBug[2];
                            weakSelf.imageView4.image =weakSelf.array_FixBug[3];
                        }
                    }
                }
            }else{
                weakSelf.ImageViews.image =[originImage copy][0];
                weakSelf.ImageViews2.image =[originImage copy][originImage.count-3];
                //    self.ImageViews2.tag =1002;
                weakSelf.imageView3.image =[originImage copy][originImage.count-2];
                weakSelf.imageView4.image =[originImage copy][originImage.count-1];  
            }

            //    self.imageView4.tag =1004;
            
            
            
        };*/
        [weakSelf presentViewController:dvc animated:YES completion:nil];
    
//    });
//
//
//     });
}
#pragma  mark 重新认证
- (IBAction)reImageAuthenticationbutton:(id)sender {
    [self KZViewControllerEnter];

}
#pragma mark -KZDelegate
#pragma mark -错报图标
- (IBAction)senderToHiddenView:(id)sender {
    self.backguardView.hidden =YES;
    [self.navigationController popViewControllerAnimated:YES];
    //return;
       // [self KZViewControllerEnter];
}

#pragma  mark 三个按钮
-(void)selectPicToChangeImageView
{
    NSArray *radioArray = @[_buttonControl4,_buttonControl1, _buttonControl2, _buttonControl3];
    for (int i=0; i<radioArray.count; ++i)
    {
        CLMarkButton *button = radioArray[i];
        button.type = CLMarkTypeSingleCheck;
        button.groupId = 10001;
        button.kCheckSelectedImage=@"";
        button.tag = i;
         [button setImage:[UIImage imageNamed:@"ImageCover-10"]forState:UIControlStateSelected];
       
        [button addTarget:self action:@selector(buttonClick:) forControlEvents:UIControlEventTouchUpInside];
    }


}


#pragma  mark 按钮点击后的监听并且选择按钮给他发出去
-(void)buttonClick:(CLMarkButton *)sender
{
    [sender buttonDidClick];
    self.backguardView.hidden = YES;
    if (sender.selected == NO) {
        self.buttonForCameraPost.userInteractionEnabled =NO;
      
    }else
    {
        self.buttonForCameraPost.userInteractionEnabled = YES;
        self.changeButton5 =sender;
  
    }
    
    
}

#pragma  mark 点击了按钮
- (IBAction)photoAuthentication:(UIButton *)sender {
    //2017年修改
     self.backguardView.hidden =YES;
    timeForButtonCount *time=[[timeForButtonCount alloc]initMustTakeReturn:nil];
    
    [time methodWithTimeCount:self.changeButton5];
    if ( self.changeButton5 == self.buttonControl1)
    {
        [self  postmessageInToPhoto:self.ImageViews.image];
    }
    else if( self.changeButton5 == self.buttonControl2){
        
        [self  postmessageInToPhoto:self.ImageViews2.image];
    }else if( self.changeButton5== self.buttonControl3){
        [self  postmessageInToPhoto:self.imageView3.image];
    }else if ( self.changeButton5 == _buttonControl4){
        [self  postmessageInToPhoto:self.imageView4.image];
    }
    else
    {
        [self  postmessageInToPhoto:self.ImageViews.image];
    }
    
    
    
    
}
#pragma mark  点击取消diss
-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    [SVProgressHUD dismiss];

}
#pragma mark 设置活体检测代理方法
//-(void)send:(FaceStreamDetectorViewController *)bvc nextputImageNSarray:(NSMutableArray *)arrayFrameWork
//{
//    [self.view reloadInputViews];
//        //// self.ImageViews.image =   [UIImage imageWithCGImage:(__bridge CGImageRef _Nonnull)(images1) scale:1 orientation:UIImageOrientationLeftMirrored];
//        //    self.ImageViews.tag =1001;
//        //    //   /.jpeg这个方法可以通过后面的参数来设置图片的大小
//
//    if (arrayFrameWork.count == 0) {
//        //先判断有没有值
//        if (self.array_FixBug.count >0) {
//            //判断是什么类型的字符串
//            for (id obj in self.array_FixBug)
//            {
//                if([obj isKindOfClass:[UIImage class]])
//                {
//                    dispatch_async(dispatch_get_main_queue(), ^{
//                        self.ImageViews.image =self.array_FixBug[0];
//                        self.ImageViews2.image =self.array_FixBug[1];
//                        self.imageView3.image =self.array_FixBug[2];
//                        self.imageView4.image =self.array_FixBug[3];
//    });
//
//
//                }
//            }
//        }
//
//
//
//    }else{
//
//        dispatch_async(dispatch_get_main_queue(), ^{
//            self.ImageViews.image =arrayFrameWork[0];
//            self.ImageViews2.image =arrayFrameWork[1];
//            //    self.ImageViews2.tag =1002;
//            self.imageView3.image =arrayFrameWork[2];
//            self.imageView4.image =arrayFrameWork[3];
//    });
//
//
//
//
//
//    }
//
//
//
//
//        //    self.imageView4.tag =1004;
//
//
//}
//
//-(void)sendW:(FaceStreamDetectorViewControllerW *)bvc nextputImageNSarray:(NSMutableArray *)arrayFrameWork{
//    [self.view reloadInputViews];
//    //// self.ImageViews.image =   [UIImage imageWithCGImage:(__bridge CGImageRef _Nonnull)(images1) scale:1 orientation:UIImageOrientationLeftMirrored];
//    //    self.ImageViews.tag =1001;
//    //    //   /.jpeg这个方法可以通过后面的参数来设置图片的大小
//
//    if (arrayFrameWork.count == 0) {
//        //先判断有没有值
//        if (self.array_FixBug.count >0) {
//            //判断是什么类型的字符串
//            for (id obj in self.array_FixBug)
//            {
//                if([obj isKindOfClass:[UIImage class]])
//                {
//                    dispatch_async(dispatch_get_main_queue(), ^{
//                        self.ImageViews.image =self.array_FixBug[0];
//                        self.ImageViews2.image =self.array_FixBug[1];
//                        self.imageView3.image =self.array_FixBug[2];
//                        self.imageView4.image =self.array_FixBug[3];
//                    });
//
//
//                }
//            }
//        }
//
//
//
//    }else{
//
//        dispatch_async(dispatch_get_main_queue(), ^{
//            self.ImageViews.image =arrayFrameWork[0];
//            self.ImageViews2.image =arrayFrameWork[1];
//            //    self.ImageViews2.tag =1002;
//            self.imageView3.image =arrayFrameWork[2];
//            self.imageView4.image =arrayFrameWork[3];
//        });
//
//
//
//
//
//    }
//
//
//
//
//    //    self.imageView4.tag =1004;
//
//}

//人工审核的接口
- (IBAction)artificialWork:(id)sender {
//    [SVProgressHUD show];
//   [CityNetManager manualVerificationBakID:[[NSUserDefaults standardUserDefaults]objectForKey:@"bak"] andidentityNumber:[[NSUserDefaults standardUserDefaults]objectForKey:@"identityNumber"] andImage:UIImageJPEGRepresentation(self.failurePic.image,0.86) completionHandle:^(CitytoCityModel *model, NSError *error) {
//       if (model.code ==0) {
//           SVProgressHUD.minimumDismissTimeInterval=1.0;
//           [SVProgressHUD showSuccessWithStatus:@"人工提交成功"];
//           [self.navigationController popToRootViewControllerAnimated:YES];
//       }else
//       {
//           SVProgressHUD.minimumDismissTimeInterval=1.0;
//           [SVProgressHUD showErrorWithStatus:@"失败"];
//       }
//   }];
    //获取控制器

    UIStoryboard *sb  =[UIStoryboard storyboardWithName:@"Main" bundle:nil];
    artificalViewController *artVC=[sb instantiateViewControllerWithIdentifier:@"artificalViewController"];
    //传递数据
    //这里做了修改2017年6月27日~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~下面注释掉会旋转90
 //   self.failurePic.image  = [UIImage imageWithCGImage:self.failurePic.image.CGImage
   //                                     scale:1.0 orientation: UIImageOrientationUpMirrored];
    //2017年6月27日~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~下面注释掉会旋转90
//   self.failurePic.image=  [self imageByScalingAndCroppingForSize:CGSizeMake(664, 483) and:self.failurePic.image];
    //2017年6月27日~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    artVC.failurePic = self.failurePic.image;
    artVC.telPhone =self.telPhone;
    //测试代码----------
//       NSString *targetPath_3333=[self.documentsPath_3 stringByAppendingPathComponent:@"1test人工认证.jpg"];
//       [UIImagePNGRepresentation(self.failurePic.image) writeToFile:targetPath_3333 atomically:YES];
    

    [self.navigationController pushViewController:artVC animated:YES];
    
    
    
    
    
    
}
- (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
    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)
        NSLog(@"could not scale image");
    
    //pop the context to get back to the default
    UIGraphicsEndImageContext();
    return newImage;
}

//旋转90
+ (UIImage *)image:(UIImage *)image rotation:(UIImageOrientation)orientation

{
    
    long double rotate = 0.0;
    
    CGRect rect;
    
    float translateX = 0;
    
    float translateY = 0;
    
    float scaleX = 1.0;
    
    float scaleY = 1.0;
    
    
    
    switch (orientation) {
            
        case UIImageOrientationLeft:
            
            rotate = M_PI_2;
            
            rect = CGRectMake(0, 0, image.size.height, image.size.width);
            
            translateX = 0;
            
            translateY = -rect.size.width;
            
            scaleY = rect.size.width/rect.size.height;
            
            scaleX = rect.size.height/rect.size.width;
            
            break;
            
        case UIImageOrientationRight:
            
            rotate = 3 * M_PI_2;
            
            rect = CGRectMake(0, 0, image.size.height, image.size.width);
            
            translateX = -rect.size.height;
            
            translateY = 0;
            
            scaleY = rect.size.width/rect.size.height;
            
            scaleX = rect.size.height/rect.size.width;
            
            break;
            
        case UIImageOrientationDown:
            
            rotate = M_PI;
            
            rect = CGRectMake(0, 0, image.size.width, image.size.height);
            
            translateX = -rect.size.width;
            
            translateY = -rect.size.height;
            
            break;
            
        default:
            
            rotate = 0.0;
            
            rect = CGRectMake(0, 0, image.size.width, image.size.height);
            
            translateX = 0;
            
            translateY = 0;
            
            break;
            
    }
    
    
    
    //UIGraphicsBeginImageContext(rect.size);
    UIGraphicsImageRenderer*re=[[UIGraphicsImageRenderer alloc] initWithSize:rect.size];
    CGContextRef context = UIGraphicsGetCurrentContext();
    
    //做CTM变换
    
    CGContextTranslateCTM(context, 0.0, rect.size.height);
    
    CGContextScaleCTM(context, 1.0, -1.0);
    
    CGContextRotateCTM(context, rotate);
    
    CGContextTranslateCTM(context, translateX, translateY);
    
    
    
    CGContextScaleCTM(context, scaleX, scaleY);
    
    //绘制图片
    
    CGContextDrawImage(context, CGRectMake(0, 0, rect.size.width, rect.size.height), image.CGImage);
    
    
    
    UIImage *newPic = UIGraphicsGetImageFromCurrentImageContext();
    
    
    
    return newPic;
    
}

- ( UIImage *)imageWithImageSimple:( UIImage *)image scaledToSize:( CGSize )newSize

{
    
    // Create a graphics image context
    
    //UIGraphicsBeginImageContext (newSize);
    UIGraphicsImageRenderer*re=[[UIGraphicsImageRenderer alloc] initWithSize:newSize];
    // Tell the old image to draw in this new context, with the desired
    
    // new size
    
    [image drawInRect : CGRectMake ( 0 , 0 ,newSize. width ,newSize. height )];
    
    // Get the new image from the context
    
    UIImage * newImage = UIGraphicsGetImageFromCurrentImageContext ();
    
    // End the context
    
    UIGraphicsEndImageContext ();
    
    // Return the new image.
    
    return newImage;
    
}

-(void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    [JANALYTICSService startLogPageView:@"社保认证 - 人脸提交比对"];
    [MobClick beginLogPageView:@"社保认证 - 人脸提交比对"];
}
-(void)viewDidDisappear:(BOOL)animated{
    
    [super viewDidDisappear:animated];
    [JANALYTICSService stopLogPageView:@"社保认证 - 人脸提交比对"];
    [MobClick endLogPageView:@"社保认证 - 人脸提交比对"];

}
@end
