//
//  SecondSocialViewController.m
//  Open
//
//  Created by 看看智能 on 2017/3/16.
//  Copyright © 2017年 黄江涛 . All rights reserved.
//

#import "SecondSocialViewController.h"
#import <AssetsLibrary/AssetsLibrary.h>
#import "successViewController.h"
#import "UIImage+Custom.h"


//指明枚举类型





@interface SecondSocialViewController ()<UIImagePickerControllerDelegate,UINavigationControllerDelegate>
//按钮一
@property (weak, nonatomic) IBOutlet UIButton *caiji;
//按钮二
@property (weak, nonatomic) IBOutlet UIButton *caiji_2;
//按钮三
@property (weak, nonatomic) IBOutlet UIButton *caiji_3;
//提交的按钮
@property (weak, nonatomic) IBOutlet UIButton *editButn;
//重新采集的按钮
@property (weak, nonatomic) IBOutlet UIButton *reGather;
//认证的按钮
@property (weak, nonatomic) IBOutlet UIButton *renzhenghecaiji;

@property(nonatomic,strong)UIImage *image_1;
@property(nonatomic,strong)UIImage *image_2;

//图片一
@property (weak, nonatomic) IBOutlet UIImageView *imageView_1;
//图片二
@property (weak, nonatomic) IBOutlet UIImageView *imageView_2;
//图片三
@property (weak, nonatomic) IBOutlet UIImageView *imageView_3;
//图片四
@property (weak, nonatomic) IBOutlet UIImageView *imageView_4;
//活体检测
//失败的时候显示的界面
@property (weak, nonatomic) IBOutlet UIView *failureView;


@property(nonatomic)NSInteger imageCount;
@property(nonatomic,strong)NSString *documentsPath_3;

/*
 * 新的界面分享
 1.分享的view
 2.按钮微信
 3.按钮支付宝
 */

//分享的文字
@property (weak, nonatomic) IBOutlet UITextView *shareTextField;

//新的分享需要一开始隐藏的view
@property (weak, nonatomic) IBOutlet UIView *shareHide;
//微信分享
@property(nonatomic,strong)UIView *view_f;
//支付宝分享

//头上显示的字
@property (weak, nonatomic) IBOutlet UILabel *nameShare;

//支付界面的view
@property (weak, nonatomic) IBOutlet UIView *ApplePayView;
@property (weak, nonatomic) IBOutlet UILabel *applePayLabel;
//支付的接口_产品编号
@property(nonatomic,strong)NSString *product_no;

//changePicSize
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *changpicSizeContrastPic_1;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *changpicSizeContrast_2;



#define MHSafeString(str) (str == nil ? @"" : str)
@end

@implementation SecondSocialViewController

-(NSString *)documentsPath_3{
    if (!_documentsPath_3) {
        //        _documentsPath_3=NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES)[0];
        _documentsPath_3 =NSSearchPathForDirectoriesInDomains(NSCachesDirectory,NSUserDomainMask,YES)[0];
    }
    return _documentsPath_3;
}

-(NSMutableArray *)baocun
{
    if (!_baocun) {
        _baocun =[NSMutableArray  new];
    }
    return _baocun;
}
-(NSMutableArray *)baocun_fixBug
{
    if (!_baocun_fixBug) {
        _baocun_fixBug =[NSMutableArray  new];
    }
    return _baocun_fixBug;
    
    
}

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:YES];
    if( self.baocun.count >=2){
        self.caiji.userInteractionEnabled =NO;
        self.caiji_3.userInteractionEnabled =NO;
        
    }else{
        
        self.caiji.userInteractionEnabled =YES;
        self.caiji_3.userInteractionEnabled =YES;
    }
    

}


 WEBS
-(void)buttonClick_1{    ZHINENGKEFU}
- (void)viewDidLoad {
    [super viewDidLoad];
self.title=@"人脸采集";
self.view.backgroundColor =[UIColor whiteColor];
    self.nameShare.text = self.social.nText;
              self.shareTextField.text =[NSString stringWithFormat:@"\t我们家乡%@%@%@可以刷脸社保认证了，足不出户、足不出村、放心领钱！\n\t看看社保，科技惠民、科技便民，人工智能走入寻常百姓家。", MHSafeString(self.social.province.text),MHSafeString(self.social.downTown.text),MHSafeString(self.social.area.text) ];
//    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;
    //百度活体检测
    [[NSUserDefaults standardUserDefaults ]setInteger:1 forKey:@"huoti_kankan_int"];
    [[NSUserDefaults standardUserDefaults]synchronize];
    //将第一个按钮也改为YES
    self.failureView.hidden = YES;
    self.caiji.hidden = YES;
    self.caiji_2.hidden = YES;
    self.caiji_3.hidden = YES;
 self.shareHide.hidden = YES;
    self.caji_0.hidden =YES;

    [self ufffblackground];//分享
    self.imageCount =1;

//UI改变按钮变成圆形
    self.editButn.layer.masksToBounds=YES;
    self.editButn.layer.cornerRadius =10;
    self.reGather.layer.masksToBounds=YES;
    self.reGather.layer.cornerRadius =10;
//活体检测赋值
    
   
     if (self.imageView_1.image == nil && ![self.greenValues  isEqualToString:@"绿色通道"] && self.baocun.count >2) {
         self.renzhenghecaiji.hidden =YES;
         [self.baocun_fixBug removeAllObjects];
         [self.baocun_fixBug addObjectsFromArray:[self.baocun copy]];
        
    self.imageView_1.image =self.baocun[0];
    self.imageView_2.image =self.baocun[1];
    self.imageView_3.image =self.baocun[2];
    self.imageView_4.image =self.baocun[3];
    
     }else if([self.greenValues  isEqualToString:@"绿色通道"]){
           [self changeBase64:_image1];
         //手动采集的接口
           self.imageView_1.image =_image1;
//self.imageView_1.image =[self imageByScalingAndCroppingForSize:CGSizeMake(270, 360) and:_image1];
       //  self.changpicSizeContrastPic_1.active =false;
//         self.changpicSizeContrastPic_1 =
//          self.changpicSizeContrast_2.multiplier=3/4;
         //采集
         
         if (self.state ==GreenRenZheng) {
             //认证
//             [self.imageView_2 removeFromSuperview];
//             self.imageView_1.translatesAutoresizingMaskIntoConstraints = NO;
//             ///////
//
//             UIImageView *imageasd = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width,[UIScreen mainScreen].bounds.size.height - 200)];
//             imageasd.image =[UIImage imageNamed:@"就业采集蓝色背景1:4"];
//              [self.view addSubview:imageasd];
//             [self.view sendSubviewToBack:imageasd];
//             //////////
//
//             NSLayoutConstraint *heightConstraint = [NSLayoutConstraint constraintWithItem:_imageView_1 attribute:NSLayoutAttributeCenterX relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeCenterX multiplier:1.0 constant:0.0];
//             [self.view addConstraint:heightConstraint];
//
//             //无法变成直角清明之后再研究一下
//
//             self.imageView_1.contentMode =UIViewContentModeScaleAspectFit;
//             self.reGather.hidden =YES;
//             self.editButn.hidden = YES;
//             [self.caiji removeFromSuperview];
             
             
             
             
             
             self.caiji.hidden = NO;
             self.caji_0.hidden =NO;
           
             self.caiji_3.hidden = YES;
             [self.caiji setBackgroundImage:[UIImage imageNamed:@"0928绿色通道添加.jpg"] forState:0];

             self.reGather.hidden =YES;
             self.editButn.hidden = YES;
          
             
             
             
         }else if (self.state == GreenCaiJi){
             [self.caiji setBackgroundImage:[UIImage imageNamed:@"0928绿色通道添加.jpg"] forState:0];
        
             self.caiji.hidden = NO;
             self.caji_0.hidden =NO;
           
             self.caiji_3.hidden = YES;
             self.reGather.hidden =YES;
             self.editButn.hidden = YES;
         }
     }
    
    
    
    
    
    //你需要做一些调用苹果内部付款的操作
  
    self.isWaidi_2 =NO;
    
    self.ApplePayView.hidden  = YES;
    if (self.state == GreenCaiJi || self.state == NormolType) {

        
        [self applePay];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(ageAchange:) name:@"KankanApplePay" object:nil];
        
//        if ([getPeopleID getpeopleLimited] == YES) {
//            self.isWaidi=NO;
//            self.isWaidi_2=NO;
//
//        }else{
//            [self applePay];
//            [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(ageAchange:) name:@"KankanApplePay" object:nil];
//        }
        
    }
    

    
    

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

-(void)ageAchange:(NSNotification*)not{

    NSLog(@"sdsad%@",not.object);

    NSString * ingsf =(NSString *)not.object;
    
    
    dispatch_async(dispatch_get_main_queue(), ^{
        
        if ([ingsf isEqualToString:@"success"]) {
            //
            self.isWaidi = NO;
             self.isWaidi_2 =NO;
              [self editButLuoJi];
        }else if([ingsf isEqualToString:@"failure"]){
//           self.isWaidi = NO;
//        ApplePay *app =  [ApplePay  manager];
//      [app buyProductsWithId:[NSString stringWithFormat:@"%d",100200] and:self.social.IDText.text andList:self.product_no];
    
          
            if ([getPeopleID getpeopleLimited] == YES) {
                self.isWaidi_2 =NO;
            }else{
                 self.isWaidi_2 =YES;
            }
        }
        
    });
    
    //
    
    
    
}
-(void)viewDidLayoutSubviews{
    [super viewDidLayoutSubviews];
//    self.imageView_1.layer.cornerRadius=CGRectGetWidth(self.imageView_1.frame) / 3;;// 将图层的边框设置为圆角
//    self.imageView_1.layer.masksToBounds=YES;// 隐藏边界
}


- (IBAction)caijiShebao:(id)sender {
   
    self.imageCount =2;
        [self getPhotoMethod];
}
- (IBAction)caiji_2:(id)sender {
    self.imageCount =3;
    [self getPhotoMethod];
    
}

- (IBAction)caji_3:(id)sender {
    self.imageCount =4;
    [self getPhotoMethod];
}


#define mark - 显示分享


//上传数据
-(void)updateAllGatherDate{
    
    
    
    
    
    
    
}

- (IBAction)reGatherButton:(id)sender {
    [self KZViewControllerEnter];
}








#pragma mark - camera
-(void)getPhotoMethod
{
    
  //  [self baidu];
    __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]};
    [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{
            UIImage * flippedImage =originImage[originImage.count-1];
            switch (self.imageCount) {
                case 1:
                    
                    self.imageView_1.image =originImage[originImage.count-1];
                    
                    
                    break;
                case 2:
                    [self changeBase64:flippedImage];
                    //改的位置
                   self.imageView_3.image =flippedImage;
                   // self.imageView_3.image =[self imageByScalingAndCroppingForSize:CGSizeMake(270, 360) and: flippedImage];
                   self.caiji.userInteractionEnabled =NO;
                    self.caiji_3.userInteractionEnabled =NO;
                    [self.caiji setBackgroundImage: [UIImage imageNamed:@"0928绿色通道对勾.jpg"] forState:UIControlStateNormal];
                     [self.caiji_3 setBackgroundImage: [UIImage imageNamed:@"0928绿色通道对勾.jpg"] forState:UIControlStateNormal];
                    self.caiji_2.hidden =NO;
                    //                        self.caiji_2.hidden = NO;
                    self.caiji_3.hidden =NO;
                    break;
                case 3:
                    self.imageView_3.image =flippedImage;
                    [self changeBase64:self.imageView_3.image];
                    self.caiji.hidden = YES;
                    self.caiji_2.hidden = YES;
                    self.caiji_3.hidden = NO;
                    break;
                case 4:
                    self.imageView_4.image =flippedImage;
                    [self changeBase64:self.imageView_4.image];
                    self.caiji.hidden = YES;
                    self.caiji_2.hidden = YES;
                    self.caiji_3.hidden = YES;
                    break;
                default:
                    break;
                    
            }
        }
        //finish
        
    };
    UINavigationController *navi = [[UINavigationController alloc] initWithRootViewController:dvc];
    navi.navigationBarHidden = true;
    [self presentViewController:navi animated:YES completion:nil];
    
    
    
}





-(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:^{
       
                switch (self.imageCount) {
                    case 1:
                      
                            self.imageView_1.image =flippedImage;
                        
                      
                        break;
                    case 2:
                          [self changeBase64:flippedImage];
                        self.imageView_3.image =flippedImage;
                       
                        self.caiji.userInteractionEnabled =NO;
                        self.caiji_3.userInteractionEnabled =NO;
                        [self.caiji setBackgroundImage: [UIImage imageNamed:@"0928绿色通道对勾.jpg"] forState:UIControlStateNormal];
                        [self.caiji_3 setBackgroundImage: [UIImage imageNamed:@"0928绿色通道对勾.jpg"] forState:UIControlStateNormal];
                        self.caiji_2.hidden =NO;
                        //                        self.caiji_2.hidden = NO;
                        self.caiji_3.hidden =NO;
                        break;
                    case 3:
                        self.imageView_3.image =flippedImage;
                         [self changeBase64:self.imageView_3.image];
                        self.caiji.hidden = YES;
                        self.caiji_2.hidden = YES;
                        self.caiji_3.hidden = NO;
                        break;
                    case 4:
                        self.imageView_4.image =flippedImage;
                         [self changeBase64:self.imageView_4.image];
                        self.caiji.hidden = YES;
                        self.caiji_2.hidden = YES;
                        self.caiji_3.hidden = YES;
                        break;
                    default:
                        break;
                        
                }
               
            }];
        });
    }
}
#pragma mark - 将照片等比例缩放
-(void)changeBase64:(UIImage*)image
{
    CGSize imagesize = image.size;
    NSLog(@"%lf",image.size.height);
    NSLog(@"%lf",image.size.width);
    imagesize.height =50;
    imagesize.width =50;
    //对图片大小进行压缩--
    
//    UIImage *image1=   [SecondSocialViewController imageCompressFitSizeScale:image targetSize:CGSizeMake(image.size.width/4, image.size.height/4)];

   UIImage *image1=    [self imageCompressForSize:image targetSize:CGSizeMake(483, 644)];
    //照片是对的完全没有问题,如果想加快速度必须让戴海峰配合的去弄,否则毫无办法,因为把他放在网上转base64是可以转出来的,如果想提速只要调用上面的这个方法即可.否则毫无办法,上面两个方法都是可以的
    //这里的0.3决定了照片认证的精确值
 image1 =   [SecondSocialViewController image:image1 rotation:UIImageOrientationLeft];
    NSData *str2=UIImageJPEGRepresentation(image1, 0.4);

//    //test------------------------------
//    image1 =nil;
//    imag1 = [UIImage imageWithData:str2];


    //test----------------------------------------------------------------------------------------------------------------------------------
    image1 = nil;
    image1 = [UIImage imageWithData:str2];
    //这里面我放了测试代码
    
    NSString *targetPath_3333=[self.documentsPath_3 stringByAppendingPathComponent:@"12yue13ri采集照片_2.jpg"];
    [UIImagePNGRepresentation(image1) writeToFile:targetPath_3333 atomically:YES];
        //test----------------------------------------------------------------------------------------------------------------------------------
    
//    NSData *str2 =UIImagePNGRepresentation(image1);
 NSString *str3=[EnercryTool encryptBase64:str2];
    NSLog(@"%ld",(unsigned long)[str3 length]);
    [self.baocun addObject:str3];
    

}



-(void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
    [picker dismissViewControllerAnimated:YES completion:^{
    }];
}

-(UIImage*)imageWithImage:(UIImage*)image scaledToSize:(CGSize)newSize
{
    // Create a graphics image context
    UIGraphicsBeginImageContext(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;
}
+ (UIImage *) imageCompressFitSizeScale:(UIImage *)sourceImage targetSize:(CGSize)size{
    UIImage *newImage = nil;
    CGSize imageSize = sourceImage.size;
    CGFloat width = imageSize.width;
    CGFloat height = imageSize.height;
    CGFloat targetWidth = size.width;
    CGFloat targetHeight = size.height;
    CGFloat scaleFactor = 0.0;
    CGFloat scaledWidth = targetWidth;
    CGFloat scaledHeight = targetHeight;
    CGPoint thumbnailPoint = CGPointMake(0.0, 0.0);
    
    if(CGSizeEqualToSize(imageSize, size) == NO){
        
        CGFloat widthFactor = targetWidth / width;
        CGFloat heightFactor = targetHeight / height;
        
        if(widthFactor > heightFactor){
            scaleFactor = widthFactor;
            
        }
        else{
            
            scaleFactor = heightFactor;
        }
        scaledWidth = width * scaleFactor;
        scaledHeight = height * scaleFactor;
        
        if(widthFactor > heightFactor){
            
            thumbnailPoint.y = (targetHeight - scaledHeight) * 0.5;
        }else if(widthFactor < heightFactor){
            
            thumbnailPoint.x = (targetWidth - scaledWidth) * 0.5;
        }
    }
    
    UIGraphicsBeginImageContext(size);
    
    CGRect thumbnailRect = CGRectZero;
    thumbnailRect.origin = thumbnailPoint;
    thumbnailRect.size.width = scaledWidth;
    thumbnailRect.size.height = scaledHeight;
    
    [sourceImage drawInRect:thumbnailRect];
    
    newImage = UIGraphicsGetImageFromCurrentImageContext();
    if(newImage == nil){
        NSLog(@"scale image fail");
    }
    
    UIGraphicsEndImageContext();
    return newImage;
}
//等比例缩放

-(UIImage *)imageCompressForSize:(UIImage *)sourceImage targetSize:(CGSize)size{
    
    
    UIImage *newImage = nil;
    
    CGSize imageSize = sourceImage.size;
    
    CGFloat width = imageSize.width;
    
    CGFloat height = imageSize.height;
    
    CGFloat targetWidth = size.width;
    
    CGFloat targetHeight = size.height;
    
    CGFloat scaleFactor = 0.0;
    
    CGFloat scaledWidth = targetWidth;
    
    CGFloat scaledHeight = targetHeight;
    
    CGPoint thumbnailPoint = CGPointMake(0.0, 0.0);
    
    
    if(CGSizeEqualToSize(imageSize, size) == NO){
        
        
        CGFloat widthFactor = targetWidth / width;
        
        CGFloat heightFactor = targetHeight / height;
        
        
        if(widthFactor > heightFactor){
            
            scaleFactor = widthFactor;
            
            
        }
        
        else{
            
            
            scaleFactor = heightFactor;
            
        }
        
        scaledWidth = width * scaleFactor;
        
        scaledHeight = height * scaleFactor;
        
        
        if(widthFactor > heightFactor){
            
            
            thumbnailPoint.y = (targetHeight - scaledHeight) * 0.5;
            
        }else if(widthFactor < heightFactor){
            
            
            thumbnailPoint.x = (targetWidth - scaledWidth) * 0.5;
            
        }
        
    }
    
    
    UIGraphicsBeginImageContext(size);
    
    
    CGRect thumbnailRect = CGRectZero;
    
    thumbnailRect.origin = thumbnailPoint;
    
    thumbnailRect.size.width = scaledWidth;
    
    thumbnailRect.size.height = scaledHeight;
    
    
    [sourceImage drawInRect:thumbnailRect];
    
    
    newImage = UIGraphicsGetImageFromCurrentImageContext();
    
    if(newImage == nil){
        
        NSLog(@"scale image fail");
        
    }
    
    
    UIGraphicsEndImageContext();
    
    return newImage;
    
}

- (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;
    }
    
    
    
}
///截取部分图像
-(UIImage*)getSubImagessss:(CGRect)rect andImage:(UIImage*)image
{
    CGImageRef subImageRef = CGImageCreateWithImageInRect(image.CGImage, rect);
    CGRect smallBounds = CGRectMake(0, 0, CGImageGetWidth(subImageRef), CGImageGetHeight(subImageRef));
    
    UIGraphicsBeginImageContext(smallBounds.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextDrawImage(context, smallBounds, subImageRef);
    UIImage* smallImage = [UIImage imageWithCGImage:subImageRef];
    UIGraphicsEndImageContext();
    
    CGImageRelease(subImageRef);
    
    return smallImage;
}
//逆时针旋转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);
    
    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;
    
}
#define mark - 微信分享
-(void)shared:(UMShareWebpageObject*)shareObject andM:(UMSocialMessageObject*)messageObject andP:(UMSocialPlatformType)platformType
{
    

    //设置网页地址
    shareObject.webpageUrl = UMS_WebLink;
    
    //分享消息对象设置分享内容对象
    messageObject.shareObject = shareObject;
    
    //调用分享接口
    [[UMSocialManager defaultManager] shareToPlatform:platformType messageObject:messageObject currentViewController:self completion:^(id data, NSError *error) {
        if (error) {
            UMSocialLogInfo(@"************Share fail with error %@*********",error);
        }else{
            if ([data isKindOfClass:[UMSocialShareResponse class]]) {
                UMSocialShareResponse *resp = data;
                //分享结果消息
                UMSocialLogInfo(@"response message is %@",resp.message);
                //第三方原始返回的数据
                UMSocialLogInfo(@"response originalResponse data is %@",resp.originalResponse);
                
            }else{
                UMSocialLogInfo(@"response data is %@",data);
            }
        }
        [self alertWithError:error];
    }];
    
    
}
- (void)shareWebPageToPlatformType:(UMSocialPlatformType)platformType
{
    //创建分享消息对象
    UMSocialMessageObject *messageObject = [UMSocialMessageObject messageObject];
            NSString *shareTitle =[NSString stringWithFormat:@"我们家乡%@%@%@可以刷脸社保认证了，足不出户、足不出村、放心领钱！\n看看社保，科技惠民、科技便民，人工智能走入寻常百姓家。", MHSafeString(self.social.province.text),MHSafeString(self.social.downTown.text),MHSafeString(self.social.area.text) ];
    //创建网页内容对象
    NSString* thumbURL =  UMS_THUMB_IMAGE;
    if (platformType  == UMSocialPlatformType_WechatSession) {

        UMShareWebpageObject *shareObject = [UMShareWebpageObject shareObjectWithTitle:UMS_Title descr:shareTitle
                                               thumImage:thumbURL];
        
        [self shared:shareObject andM:messageObject andP:platformType];
        
    }else if (platformType == UMSocialPlatformType_WechatTimeLine){
        UMShareWebpageObject *shareObject = [UMShareWebpageObject shareObjectWithTitle:shareTitle descr:shareTitle thumImage:thumbURL];
        [self shared:shareObject andM:messageObject andP:platformType];
    }
    
}


- (void)alertWithError:(NSError *)error
{
    NSString *result = nil;
    if (!error) {
        result = [NSString stringWithFormat:@"分享成功"];
  
    }
    else{
        NSMutableString *str = [NSMutableString string];
        if (error.userInfo) {
            for (NSString *key in error.userInfo) {
                [str appendFormat:@"%@ = %@\n", key, error.userInfo[key]];
            }
        }
        if (error) {
            result = [NSString stringWithFormat:@"Share fail with error code: %d\n%@",(int)error.code, str];
            result = [NSString stringWithFormat:@"分享失败"];
      
        }
        else{
            result = [NSString stringWithFormat:@"Share fail"];
        }
    }
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil
                                                    message:result
                                                   delegate:nil
                                          cancelButtonTitle:NSLocalizedString(@"确定", @"确定")
                                          otherButtonTitles:nil];
    [alert show];
}

- (IBAction)cloaseAll:(UIButton *)sender {
    
    switch (sender.tag) {
        case 9905:
            //微信聊天
            [self shareWebPageToPlatformType:UMSocialPlatformType_WechatSession];
            break;
        case 9906:
             [self shareWebPageToPlatformType:UMSocialPlatformType_WechatTimeLine];
            break;
        case 9907:
            //关闭
            self.shareHide.hidden = YES;
//            [self.view_f removeFromSuperview];
            self.view_f.hidden =YES;

            [self backMain];
            break;
        default:
            break;
    }
    
    
}
-(void)backMain{
//    dispatch_async(dispatch_get_main_queue(), ^{
        [self.shareHide removeFromSuperview];
          [self.view_f removeFromSuperview];
    
        [self.navigationController popToRootViewControllerAnimated:YES];
     
//    });
    
}
-(void)ufffblackground
{
    //分享的
    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/255.0 green:0/255.0 blue:0/255.0 alpha:0.5];
    //添加一个动画,渐变的效果
    CATransition *applicationLoadViewIn =[CATransition animation];
    [applicationLoadViewIn setDuration:0.4];
    [applicationLoadViewIn setType:kCATransitionReveal];
    [applicationLoadViewIn setTimingFunction:[CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseIn]];
    //you view need to replace
    [[self.view_f layer]addAnimation:applicationLoadViewIn forKey:kCATransitionReveal];
    [[self.shareHide layer]addAnimation:applicationLoadViewIn forKey:kCATransitionReveal];
        [[self.ApplePayView layer]addAnimation:applicationLoadViewIn forKey:kCATransitionReveal];
    UITapGestureRecognizer * tap_=[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapAvatarVw)];
    [self.view_f addGestureRecognizer:tap_];
    [self.view addSubview:self.view_f];
    [self.view bringSubviewToFront:self.shareHide];
    
    self.view_f.hidden = YES;
}
-(void)tapAvatarVw{
    self.shareHide.hidden = YES;
    [self.view_f removeFromSuperview];
    //    [self.navigationController popToRootViewControllerAnimated:YES];
    
    [self backMain];
    
    
}

#pragma mark - 活体检测
//-(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.baocun_fixBug.count >0) {
//            //判断是什么类型的字符串
//            for (id obj in self.baocun_fixBug)
//            {
//                if([obj isKindOfClass:[UIImage class]])
//                {
//                    dispatch_async(dispatch_get_main_queue(), ^{
//                        self.imageView_1.image =self.baocun_fixBug[0];
//                        self.imageView_2.image =self.baocun_fixBug[1];
//                        self.imageView_3.image =self.baocun_fixBug[2];
//                        self.imageView_4.image =self.baocun_fixBug[3];
//                    });
//
//
//                }
//            }
//        }
//    }else{
//
//        dispatch_async(dispatch_get_main_queue(), ^{
//            self.imageView_1.image =arrayFrameWork[0];
//            self.imageView_2.image =arrayFrameWork[1];
//            //    self.ImageViews2.tag =1002;
//            self.imageView_3.image =arrayFrameWork[2];
//            self.imageView_4.image =arrayFrameWork[3];
//            [self.baocun removeAllObjects];
//            [self.baocun addObject:arrayFrameWork[0]];
//            [self.baocun addObject:arrayFrameWork[1]];
//            [self.baocun addObject:arrayFrameWork[2]];
//            [self.baocun addObject:arrayFrameWork[3]];
//        });
//
//
//    }
//
//
//
//
//    //    self.imageView4.tag =1004;
//
//
//}
//
//
//-(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.baocun_fixBug.count >0) {
//            //判断是什么类型的字符串
//            for (id obj in self.baocun_fixBug)
//            {
//                if([obj isKindOfClass:[UIImage class]])
//                {
//                    dispatch_async(dispatch_get_main_queue(), ^{
//                        self.imageView_1.image =self.baocun_fixBug[0];
//                        self.imageView_2.image =self.baocun_fixBug[1];
//                        self.imageView_3.image =self.baocun_fixBug[2];
//                        self.imageView_4.image =self.baocun_fixBug[3];
//    });
//
//
//                }
//           }
//        }
//    }else{
//
//        dispatch_async(dispatch_get_main_queue(), ^{
//            self.imageView_1.image =arrayFrameWork[0];
//            self.imageView_2.image =arrayFrameWork[1];
//            //    self.ImageViews2.tag =1002;
//            self.imageView_3.image =arrayFrameWork[2];
//            self.imageView_4.image =arrayFrameWork[3];
//            [self.baocun removeAllObjects];
//            [self.baocun addObject:arrayFrameWork[0]];
//            [self.baocun addObject:arrayFrameWork[1]];
//            [self.baocun addObject:arrayFrameWork[2]];
//            [self.baocun addObject:arrayFrameWork[3]];
//    });
//
//
//    }
//
//
//
//
//    //    self.imageView4.tag =1004;
//
//
//}

-(void)KZViewControllerEnter
{
    //    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
    dispatch_async(dispatch_get_main_queue(), ^{

//        if ([getPeopleID getpeopleLimited] == YES) {
        
            
//            if ([self.greenValues isEqualToString:@"绿色通道"]) {
//                FaceStreamDetectorViewControllerW *faceVC = [[FaceStreamDetectorViewControllerW  alloc]init];
//                faceVC.faceDelegate = self;
//                faceVC.greenValue =@"绿色通道";
//                [self presentViewController:faceVC animated:YES completion:nil];
//            }else{
//                FaceStreamDetectorViewControllerW *faceVC = [[FaceStreamDetectorViewControllerW  alloc]init];
//                faceVC.faceDelegate = self;
//                [self presentViewController:faceVC animated:YES completion:nil];
//
//            }
//
//
//
//        }else{
//            if ([self.greenValues isEqualToString:@"绿色通道"]) {
//                FaceStreamDetectorViewController *faceVC = [[FaceStreamDetectorViewController  alloc]init];
//                faceVC.faceDelegate = self;
//                faceVC.greenValue =@"绿色通道";
//                [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.view reloadInputViews];
                //// self.ImageViews.image =   [UIImage imageWithCGImage:(__bridge CGImageRef _Nonnull)(images1) scale:1 orientation:UIImageOrientationLeftMirrored];
                //    self.ImageViews.tag =1001;
                //    //   /.jpeg这个方法可以通过后面的参数来设置图片的大小
                if (originImage.count > 3) {
                    //先判断有没有值
//                    if (weakSelf.baocun_fixBug.count >0) {
//                        //判断是什么类型的字符串
//
//
//                            if([weakSelf.baocun_fixBug[3] isKindOfClass:[UIImage class]])
//                            {
//
//                                    weakSelf.imageView_1.image =weakSelf.baocun_fixBug[0];
//                                    weakSelf.imageView_2.image =weakSelf.baocun_fixBug[1];
//                                    weakSelf.imageView_3.image =weakSelf.baocun_fixBug[2];
//                                    weakSelf.imageView_4.image =weakSelf.baocun_fixBug[3];
//
//
//
//
//
//                        }
//                    }
                    weakSelf.imageView_1.image =[originImage copy][0];
                    weakSelf.imageView_2.image =[originImage copy][originImage.count-3];
                    //    self.ImageViews2.tag =1002;
                    weakSelf.imageView_3.image =[originImage copy][originImage.count-2];
                    weakSelf.imageView_4.image =[originImage copy][originImage.count-1];
                    [weakSelf.baocun removeAllObjects];
                    [weakSelf.baocun addObject:[originImage copy][0]];
                    [weakSelf.baocun addObject:[originImage copy][originImage.count-3]];
                    [weakSelf.baocun addObject:[originImage copy][originImage.count-2]];
                    [weakSelf.baocun addObject:[originImage copy][originImage.count-1]];
                    
                    
                }else{
                    
                                        if (weakSelf.baocun_fixBug.count >0) {
                                            //判断是什么类型的字符串
                    
                    
                                                if([weakSelf.baocun_fixBug[3] isKindOfClass:[UIImage class]])
                                                {
                    
                                                        weakSelf.imageView_1.image =weakSelf.baocun_fixBug[0];
                                                        weakSelf.imageView_2.image =weakSelf.baocun_fixBug[1];
                                                        weakSelf.imageView_3.image =weakSelf.baocun_fixBug[2];
                                                        weakSelf.imageView_4.image =weakSelf.baocun_fixBug[3];
                    
                    
                    
                    
                    
                                            }
                                        }
//                    weakSelf.imageView_1.image =[originImage copy][0];
//                    weakSelf.imageView_2.image =[originImage copy][originImage.count-3];
//                    //    self.ImageViews2.tag =1002;
//                    weakSelf.imageView_3.image =[originImage copy][originImage.count-2];
//                    weakSelf.imageView_4.image =[originImage copy][originImage.count-1];
//                    [weakSelf.baocun removeAllObjects];
//                    [weakSelf.baocun addObject:[originImage copy][0]];
//                    [weakSelf.baocun addObject:[originImage copy][originImage.count-3]];
//                    [weakSelf.baocun addObject:[originImage copy][originImage.count-2]];
//                    [weakSelf.baocun addObject:[originImage copy][originImage.count-1]];
                    
                    
                    
                }
                
                
                
                
                //    self.imageView4.tag =1004;
                
                
            };
            [weakSelf presentViewController:dvc animated:YES completion:nil];
            
            
            
        
        
        
        
        
        
        
        
        
        

        
        
        
        
    });
    
    
    //     });
}
//人工采集按钮
- (IBAction)humunGather:(id)sender {
    UIStoryboard *sb  =[UIStoryboard storyboardWithName:@"Main" bundle:nil];
    artificalViewController *artVC=[sb instantiateViewControllerWithIdentifier:@"artificalViewController"];
    //留着
   // artVC.failurePic = nil;
    
    UIImage *image = [JobUtil imagehuangzhuan:self.imageView_1.image rotation:UIImageOrientationLeft];
    
    artVC.failurePic = [self imageCompressForSize:image targetSize:CGSizeMake(483, 644)];
    [self.navigationController pushViewController:artVC animated:YES];
    
}



//重新采集的按钮
- (IBAction)reGatherSecond:(id)sender {
//    [self KZViewControllerEnter];
    self.failureView.hidden =YES;
    [self getPhotoMethod];
}

//保存照片转换逻辑
-(NSString*)imageChangeType:(UIImage*)selfImage{
   
    //百度活体检测
    selfImage=  [JobUtil imagehuangzhuan:selfImage rotation:UIImageOrientationLeft];
     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;
  
}

#pragma mark - 苹果的内部付款_1
- (IBAction)butTag:(UIButton *)sender {
    
    //6913 支付
    
    
    
    //6912 取消
    switch (sender.tag) {
        case 6912:
            // 返回
            self.ApplePayView.hidden = YES;
    
            self.view_f.hidden =YES;
            break;
            
        case 6913:
            // //继续
            [self zhifu];
            break;
        default:
            break;
            
            
            
    }
}
-(void)zhifu{
    
    //支付接口
    self.ApplePayView.hidden = YES;
    self.view_f.hidden =YES;
  //这里可以用product_no来代替
     [SVProgressHUD shows];
    ApplePay *app =  [ApplePay  manager];
    //1.id
    //2.bianhao
    
    if (self.isWaidi_2 == YES) {
        [app verifyTransactionResult:nil];
    }else{
        
        [app buyProductsWithId:[NSString stringWithFormat:@"%d",100200] and:self.social.IDText.text andList:self.product_no];

    }

}

-(void)laozuoJieKou{
    //test
    __weak __typeof(self)weakSelf = self;
    //调用老左的接口获取数据
    [getAppleyPayGeogle getValidateIsOrNotPay:nil abd:self.social.IDText.text completionHandle:^(ApplePays *model, NSError *error) {
        if (model.result.orderDetail == nil && model.code == 1017) {
            [SVProgressHUD showErrorWithStatus:@"数据解析失败"];
            
            if ([getPeopleID getpeopleLimited] == YES) {
                self.isWaidi =NO;
            }else{
                self.isWaidi =YES;
            }
            return ;
        }
        if(error) {
            [SVProgressHUD showErrorWithStatus:@"数据解析失败,请检查网络"];
          
            if ([getPeopleID getpeopleLimited] == YES) {
                self.isWaidi =NO;
            }else{
                self.isWaidi =YES;
            }
            return ;
        }
        if (model.code == 1017 || model.code ==1026 || model.code == 1019 ) {
            if(model.code == 1019){
                [SVProgressHUD showErrorWithStatus:@"订单无法生成请检测网络"];
                
            }
            weakSelf.view_f.hidden =YES;
            weakSelf.ApplePayView.hidden = YES;
            weakSelf.applePayLabel.text =[NSString stringWithFormat:@"一个身份证收取%.0lf元成本费",model.result.originalPrice];
            weakSelf.product_no =model.result.orderNo;
  
        }else{
            weakSelf.view_f.hidden =YES;
            weakSelf.ApplePayView.hidden = YES;
            weakSelf.isWaidi = NO;
        }

        
    }];
    
    
}


#pragma mark - 苹果的内部付款
-(void)applePay{
//如果是本地就不调用老左的接口
   //1.第一步  -  做个判断
//
//        ApplePays *models = model;
//        NSLog(@"%ld",(long)models.code);
//        NSLog(@"%ld",(long)models.flag);
//        ApplePaysResult *moddd = models.result;
//        NSLog(@"%@",[moddd valueForKey:@"orderName"]);
//
//        NSLog(@"%@",[moddd valueForKey:@"realPayMoney"]);
//        NSLog(@"%ld",(long)moddd.discount);
//        NSLog(@"%f",moddd.originalPrice);
    

        
        //********************************获取产品编号*********************
        //        NSData *jsonData = [model.result.orderDetail dataUsingEncoding:NSUTF8StringEncoding];
        //        NSError *err;
        //        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData
        //                                                            options:NSJSONReadingMutableContainers
        //                                                              error:&err];
        // dic[@"produce_no"];获取产品的编号
        //********************************获取产品编号*********************

             getAppleyPayGeogle *cityApplepay=   [[getAppleyPayGeogle  alloc]init];
            AppDelegate *dele=(AppDelegate*)[[UIApplication sharedApplication]delegate];
                __weak __typeof(self)weakSelf = self;
            if (dele.isLogin==NO || [[getPeopleID applePaycity] isEqualToString:@""]) {
                [cityApplepay get:weakSelf ApplePayCity:^{
                    //判断是否是外地

                    if([weakSelf.social.province.text isEqualToString:@"上海市"] || [weakSelf.social.province.text isEqualToString:@"北京市"] || [weakSelf.social.province.text isEqualToString:@"天津市"] || [weakSelf.social.province.text isEqualToString:@"重庆市"]){
                        if ([weakSelf.social.province.text isEqualToString:[getPeopleID applePaycity]]){
                            weakSelf.isWaidi = NO;
                        
                        }else{
                      
                            if ([getPeopleID getpeopleLimited] == YES) {
                                weakSelf.isWaidi =NO;
                            }else{
                                weakSelf.isWaidi =YES;
                                  [weakSelf laozuoJieKou];
                            }
                      
                        }
                    }else{
                        
                        if ([weakSelf.social.downTown.text isEqualToString:[getPeopleID applePaycity]]){
                            weakSelf.isWaidi = NO;
                        }else{
                            if ([getPeopleID getpeopleLimited] == YES) {
                                weakSelf.isWaidi =NO;
                            }else{
                                weakSelf.isWaidi =YES;
                                [weakSelf laozuoJieKou];
                            }
                        }
                    }
                    
                }];
            }else{
                if([weakSelf.social.province.text isEqualToString:@"上海市"] || [weakSelf.social.province.text isEqualToString:@"北京市"] || [weakSelf.social.province.text isEqualToString:@"天津市"] || [weakSelf.social.province.text isEqualToString:@"重庆市"]){
                    if ([weakSelf.social.province.text isEqualToString:[getPeopleID applePaycity]]){
                        weakSelf.isWaidi = NO;//no
                  
                    }else{
                        if ([getPeopleID getpeopleLimited] == YES) {
                            weakSelf.isWaidi =NO;
                        }else{
                            weakSelf.isWaidi =YES;
                            [weakSelf laozuoJieKou];
                        }
                    }
                    
                    }else{
                    

                        
                        if ([weakSelf.social.downTown.text isEqualToString:[getPeopleID applePaycity]]){
                       weakSelf.isWaidi = NO;//no
                  
                        }else{
                            if ([getPeopleID getpeopleLimited] == YES) {
                                weakSelf.isWaidi =NO;
                            }else{
                                weakSelf.isWaidi =YES;
                                [weakSelf laozuoJieKou];
                            }
                        }
                        }
            }
   
        
        
        
    
    
    
    

    
    

    
}
#pragma mark - 绿色认证按钮和采集按钮

- (IBAction)hderfsdhfsadfdgh:(id)sender {
    [self editButLuoJi];
}
#pragma mark - 提交按钮最后一步
- (IBAction)tijiaoqueren:(id)sender {
     [self  editButLuoJi];
}

#pragma mark - 提交所有的复杂逻辑
-(void)editButLuoJi{
    
    //test
   
    
    if (_isWaidi == YES) {
        //支付的接口调用
        self.ApplePayView.hidden =NO;
        self.view_f.hidden = NO;
        [self.view bringSubviewToFront:self.ApplePayView];
        return;
    }
    

    
    NSString *path =@"";
    if ([self.OffLineGather isEqualToString:@"离线采集"]) {
        path =@"离线采集";
        
        self.editButn.userInteractionEnabled =YES;
        [self.baocun removeAllObjects];
        [self.baocun addObject:[self imageChangeType:self.imageView_2.image]];
        [self.baocun addObject:[self imageChangeType:self.imageView_3.image]];
        [self.baocun addObject:[self imageChangeType:self.imageView_4.image]];
     
    }else if( self.state == GreenRenZheng ){
 
        self.editButn.userInteractionEnabled =NO;

   [SVProgressHUD doneShow];

        if (self.baocun.count ==1 ) {
            [SVProgressHUD showErrorWithStatus:@"请拍两张照片"];   
            return;
        }

        [self Luoji_2];
    
        return;
    }else if(self.state == GreenCaiJi){
        
          path =[IPDIZHI stringByAppendingString:@"/socialsecurity/kankan/greenChannelInsert"];
        self.editButn.userInteractionEnabled =NO;

        if (self.baocun.count ==1 ) {
            [SVProgressHUD showErrorWithStatus:@"请拍两张照片"];

            return;
        }

        [SVProgressHUD shows];
        
    }else{
           [SVProgressHUD shows];
        path =[IPDIZHI stringByAppendingString:@"/socialsecurity/kankan/insertInfo"];
        self.editButn.userInteractionEnabled =NO;
        [self.baocun removeAllObjects];
        [self.baocun addObject:[self imageChangeType:self.imageView_2.image]];
         [self.baocun addObject:[self imageChangeType:self.imageView_3.image]];
         [self.baocun addObject:[self imageChangeType:self.imageView_4.image]];
    }
    //处理保存回来的数组
    //test
    

    
    [CityNetManager getSuccessSenderSocialMessageInsertInfo:path getName:self.social.nText privateStringIdentityNumber:self.social.idText andProvinceName:self.social.province.text andCityName:self.social.downTown.text andCountryName:self.social.area.text andTownName:self.social.village.text andvillageName:self.social.villageCommittee.text andTelephone:self.social.phoneNumber.text andCompanyName:self.social.Company.text andFlag:2 andVerifyType:self.social.ice andUimage:self.baocun ocrIMage:self.social.ocrBase64 ocrIMage_:self.social.ocrBase64_ completionHandle:^(verifyAdressModel *model, NSError *error){
        [SVProgressHUD doneShow];
        
        
        //离线采集
        if ([self.OffLineGather isEqualToString:@"离线采集"]) {
            
            dispatch_async(dispatch_get_main_queue(), ^{
                [SVProgressHUD dismiss];
                
                socialOffLineGatherViewController *once  = [socialOffLineGatherViewController sharedInstance];
                
                
                [self.navigationController popToViewController:once animated:YES];
            });
            return;
        }
        
        
        
        
        
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            if(model.code == 0)
            { [SVProgressHUD dismiss];
                
                dispatch_async(dispatch_get_main_queue(), ^{
                    NSString *str =nil;
                    if ([getPeopleID getpeopleLimited]  ==YES) {
                        
                        str =[NSString stringWithFormat:@"%@,采集成功",self.social.nameText.text];
                    }else{
                        
                        str =[NSString stringWithFormat:@"%@,采集成功,请等待5个工作日审核身份，通过后，进行社保身份认证，认证通过后可正常领取养老金",self.social.nameText.text];
                    }
                    
                    if ([model.bak isEqualToString:@"1"]) {
                        str = nil;
                        str =@"仅识别出一张人脸,按返回重新采集";
                        UIAlertController *alertCon =[UIAlertController alertControllerWithTitle:str message:nil preferredStyle:UIAlertControllerStyleAlert];
                        [alertCon addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                        }]];
                        
                        [self presentViewController:alertCon animated:YES completion:nil];
                        return;
                    }
                    //2017年11月23日注释了
                    //    UIAlertController *alertCon =[UIAlertController alertControllerWithTitle:str message:nil preferredStyle:UIAlertControllerStyleAlert];
                    self.social.ocrBase64=nil;
                    self.social.ocrBase64_ =nil;
                    self.social.phoneNumber.text =@"";
                    //             [alertCon addAction:[UIAlertAction actionWithTitle:@"返回首页" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                    
                    //               [self backMain];
                    //        }]];
                    
                    //     [alertCon addAction:[UIAlertAction actionWithTitle:@"分享朋友圈" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
                    dispatch_async(dispatch_get_main_queue(), ^{
                        self.view_f.hidden = NO;
                        self.shareHide.hidden = NO;
                        
                    });
                    //       }]];
                    
                    
                    
                    //     [self presentViewController:alertCon animated:YES completion:nil];
                    
                });
            }else
            {
                [SVProgressHUD dismiss];
                codeSelected *code = [codeSelected MustTakeReturn:model.code];
                [code returnCodeMethod];
                return;
            }
            
        });
        self.editButn.userInteractionEnabled =YES;
        
    }];
    
    
    
    
    
    
}
// 绿色通道
-(void)Luoji_2{
    //caiji
 if (self.state == GreenRenZheng){
        //renzheng
     self.renzhenghecaiji.userInteractionEnabled = NO;
     NSUserDefaults* userDefault=[NSUserDefaults standardUserDefaults];
     NSString *names =[userDefault objectForKey:@"name"];
     NSString *identifity =[userDefault objectForKey:@"identityNumber"];
     NSString *ID =[userDefault objectForKey:@"bak"];
     NSLog(@"ID:%@",ID);
        NSString *path =@"";
       path =[IPDIZHI stringByAppendingString:@"/socialsecurity/kankan/greenChannelVerify"];
   
     UIImage *  flippedImage= self.imageView_1.image;
     self.image_1 =self.imageView_1.image;
     //这里做了修改2017年6月27日
     flippedImage  = [UIImage imageWithCGImage:flippedImage.CGImage
                                         scale:1.0 orientation: UIImageOrientationUp];
     //2017年6月27日
     //2017年7月17日 (483,664)  -->  (360,270)
     flippedImage=  [self imageByScalingAndCroppingForSize:CGSizeMake(360, 270) and:flippedImage];
     NSData  *dateImage1 =UIImageJPEGRepresentation( flippedImage,0.86);
     
     if (self.baocun.count >0) {
        [self.baocun removeObjectAtIndex:0];
     }else{
         return;
     }
   
     [CityNetManager  getaddressPhotoToThePath:path getID:ID FortheName:names theIdentityNumberPara:identifity image:dateImage1 andPhone:nil andArray:self.baocun completionHandle:^(verifyAdressModel *model, NSError *error) {
         [SVProgressHUD doneShow];
         
         NSLog(@"当前线程%@",[NSThread currentThread]);
         
         if(model.code == 0)
         {
             self.renzhenghecaiji.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:@"successSegueThree" sender:self];
         }
         else if(model.code == 1007)
         {
             self.renzhenghecaiji.userInteractionEnabled =YES;
             [SVProgressHUD dismiss];
             self.failureView.hidden = NO;
         }else if(model.code == 1012)
         {  self.renzhenghecaiji.userInteractionEnabled =YES;
             [SVProgressHUD dismiss];
             self.failureView.hidden = NO;
         }else if(model.code == 4)
         {self.renzhenghecaiji.userInteractionEnabled =YES;
             [SVProgressHUD dismiss];
             
             self.failureView.hidden = NO;
         }else if(model.code == 1015)
         {
             self.renzhenghecaiji.userInteractionEnabled =YES;
             [SVProgressHUD showErrorWithStatus:@"您人脸数据未采集,请联系所在地社保部门"];
             
         }else if(model.code == 42){
             self.renzhenghecaiji.userInteractionEnabled =YES;
             [SVProgressHUD showErrorWithStatus:@"请使用绿色通道"];
             
         }else
         {
             self.renzhenghecaiji.userInteractionEnabled =YES;
             
             [SVProgressHUD dismiss];
             self.failureView.hidden = NO;
             
         }
         //
         [SVProgressHUD dismiss];
         codeSelected *code = [codeSelected MustTakeReturn:model.code];
         [code returnCodeMethod];
         if (model.code != 0) {
             self.renzhenghecaiji.userInteractionEnabled =YES;
             
         }
         
     }];
     

    }
}

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
                           if ([segue.identifier isEqualToString:@"successSegueThree"])  {
                               
                               successViewController *blueVC = segue.destinationViewController;
                               blueVC.imageView1 =self.image_1;
                               blueVC.imageView2 =self.image_2;
                           }
                       }


@end
