 //
//  ShowPicker.m
//  Open
//
//  Created by gao on 2016/11/9.
//  Copyright © 2016年 黄江涛 . All rights reserved.
//
#import "MJExtension.h"
#import "ShowPicker.h"
#import <AVFoundation/AVFoundation.h>
#import <MediaPlayer/MediaPlayer.h>
#import "MyPickerViewController.h"
#import <MapKit/MapKit.h>
#import <CoreLocation/CoreLocation.h>
#import "XWLocationManager.h"
#import <AddressBookUI/AddressBookUI.h>
#import <Contacts/Contacts.h>
#import "CLMarkButton.h"
#import "sys/utsname.h"
#import "successViewController.h"


//雷俊博
#import "GreenChannelVC.h"

#import "AuthenticationGuideView.h"

#import "FaceImageModel.h"

@interface ShowPicker ()<UIImagePickerControllerDelegate,UINavigationControllerDelegate,MKMapViewDelegate,CLLocationManagerDelegate,UITextFieldDelegate,CLKeyboardOffsetViewDelegate,passImagesDelegate>

@property(nonatomic,strong)	 UIImageView *imageView;
@property(nonatomic,strong)	 CLLocationManager *manager;
@property(nonatomic,strong)	 NSData *nsdata;
//取出地址
@property (weak, nonatomic) IBOutlet UITextField *loactionText;
@property(nonatomic,strong)	 NSString *location;
@property(nonatomic) BOOL cityCanSender;
//保存placeMark的传过来的地址
@property(nonatomic,strong)	 NSString *pMark;

//三个按钮
@property (weak, nonatomic) IBOutlet CLMarkButton *button_1;
@property (weak, nonatomic) IBOutlet CLMarkButton *button_2;
@property (weak, nonatomic) IBOutlet CLMarkButton *button_3;

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

@property(nonatomic,strong)	 NSMutableArray *arrayImage;

@property (weak, nonatomic) IBOutlet UIImageView *middleImage;
@property (weak, nonatomic) IBOutlet UIButton *greenValue;

@property(nonatomic,strong)UIImage *image_1;
@property(nonatomic,strong)UIImage *image_2;
//top当
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *topDang;

//top参
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *topCan;



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

//top异地-本地
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *topbendi;
//top异地-国内
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *topGuonei;

//top异地-国外
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *topGuowai;

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









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

@property(nonatomic,strong)NSMutableArray *baocun;
@property(nonatomic,strong)UIView *view_ff;
@property(nonatomic)BOOL jb;
@property(nonatomic) BOOL gps;
@property(nonatomic) BOOL gogreenValue;
@end




@implementation ShowPicker


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


-(NSMutableArray *)arrayImage
{
    if (!_arrayImage) {
        _arrayImage =[[NSMutableArray alloc]init];
    }
    return _arrayImage;
}
-(void)viewWillAppear:(BOOL)animated
{
      NSString *cityPay =   self.county;
    NSLog(@"%@",cityPay);
    NSLog(@"%@",[getPeopleID applePaycity]);
    self.gps = NO;
    self.gogreenValue = NO;
     self.automaticallyAdjustsScrollViewInsets = NO;
    [super viewWillAppear:YES];
    self.haokanView.hidden =YES;
   self.loactionText.textColor = [UIColor clearColor];
     self.loactionText.font = [UIFont systemFontOfSize:14];
 
    //百度活体检测
    [[NSUserDefaults standardUserDefaults ]setInteger:1 forKey:@"huoti_kankan_int"];
    [[NSUserDefaults standardUserDefaults]synchronize];
    [[XWLocationManager sharedXWLocationManager] getCurrentLocation:^(CLLocation *location, CLPlacemark *placeMark, NSString *error) {
        if (error) {
            self.gps =NO;
            self.loactionText.text = MHSafeStrings(@"当前无法定位");
             self.dizhi.text =self.loactionText.text;
            NSLog(@"定位出错,错误信息:%@",error);
        }else{
             self.gps =YES;
            NSLog(@"定位成功:经度:%f 纬度:%lf 当前地址:%@  \n location详细信息:%@ \n ",location.coordinate.latitude, location.coordinate.longitude, placeMark.name, location);

            
            NSDictionary *addressDic = placeMark.addressDictionary;
            NSString *state=[addressDic objectForKey:@"State"];
            NSString *city=[addressDic objectForKey:@"City"];
            NSString *subLocality=[addressDic objectForKey:@"SubLocality"];
            NSString *street=[addressDic objectForKey:@"Street"];
            [self.loactionText setText:[NSString stringWithFormat:@"%@%@%@%@",
                                        MHSafeStrings(state),
                                        MHSafeStrings(city),
                                        MHSafeStrings(subLocality),
                                        //                                        MHSafeString(placeMark.thoroughfare),
                                        MHSafeStrings(street)
                                        ]];
            self.dizhi.text =self.loactionText.text;
            _pMark =  [self.province stringByAppendingString:self.county];
            NSLog(@"%@",MHSafeStrings(city));
             NSLog(@"%@",self.county);
            
            NSString *strNew =@"";
        if([self.province isEqualToString:@"上海市"] || [self.province isEqualToString:@"北京市"] || [self.province isEqualToString:@"天津市"] || [self.province isEqualToString:@"重庆市"]){
            strNew = self.province;
        }else{
            strNew = self.county;
        }
            if([MHSafeStrings(city) isEqualToString:strNew]) {//判断是否为本市的人
                self.cityCanSender =YES;
                NSLog(@"%d",self.cityCanSender);
                //判断gps 和 城市是一样的
                self.jb =YES;
            }
            

        }
    } onViewController:self];
    
    
    //禁止手势返回
    id traget = self.navigationController.interactivePopGestureRecognizer.delegate;
    UIPanGestureRecognizer * pan = [[UIPanGestureRecognizer alloc]initWithTarget:traget action:nil];
    [self.view addGestureRecognizer:pan];
}


  WEBS
-(void)buttonClick_1{    ZHINENGKEFU}

-(void)layoutSize{
    //5.5 90 高度480
    //4.7 50 高度
    //4 30  高度 390
    //3.5  10  高度 350
    if([[UIScreen mainScreen]bounds].size.height== 480){
        //4
        self.layoutCanBaoHeight.constant = 0; 
        self.layoutPicHeight.constant = 292;
        self.layoutfourheight.constant = 0;
    }else if ([[UIScreen mainScreen]bounds].size.height == 568){
        //5s
        self.layoutCanBaoHeight.constant = 10   ;
        self.layoutPicHeight.constant = 332;
        
        
    }else if ([[UIScreen mainScreen]bounds].size.height == 736){
        //iphone8plus
        self.layoutCanBaoHeight.constant = 70   ;
        self.layoutPicHeight.constant = 422;
    }else if ([[UIScreen mainScreen]bounds].size.height == 812){
       // iphonex
        self.layoutCanBaoHeight.constant = 70   ;
        self.layoutPicHeight.constant = 422;
    }else if ([[UIScreen mainScreen]bounds].size.height == 667){
//        iphone6
        self.layoutCanBaoHeight.constant = 70   ;
        self.layoutPicHeight.constant = 422;
    }
    
    self.view_ff = [[UIView alloc]initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height)];
    self.view_ff.backgroundColor =[UIColor colorWithRed:0.0/255.0 green:0.0/255.0 blue:0/255.0 alpha:0.7];
    //添加一个动画,渐变的效果
    CATransition *applicationLoadViewIn =[CATransition animation];
    [applicationLoadViewIn setDuration:0.5];
    [applicationLoadViewIn setType:kCATransitionReveal];
    [applicationLoadViewIn setTimingFunction:[CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseIn]];
    //you view need to replace
    [[self.view_ff layer]addAnimation:applicationLoadViewIn forKey:kCATransitionReveal];
    [[self.haokanView layer]addAnimation:applicationLoadViewIn forKey:kCATransitionReveal];
    
   
}
-(CGFloat)offsetViewHeightWithFirstResponder:(UIView *)firstResponder keyboardHeight:(CGFloat)keyboardHeight offsetHeight:(CGFloat)offsetHeight
{
    return  50.0;
}


- (void)viewDidLoad {
    [super viewDidLoad];
    [self.view openKeyboardOffsetView];
    self.view.keyboardOffsetViewDelegate =self;
    self.view.keyboardGap =60;
    //self.navigationController.navigationBar.translucent = NO;

  //  AppDelegate *delegate=(AppDelegate*)[[UIApplication sharedApplication]delegate];

    //电话
    
    
    if ( MHSafeStrings(self.photosModel.cityModel.param.telphoneValue) && ![MHSafeStrings(self.photosModel.cityModel.param.telphoneValue) isEqualToString:@""] ) {
     self.telIphone.text =  [EnercryTool decryptUseDES:self.photosModel.cityModel.param.telphoneValue key:DESKEY];
     
    }else{
        self.telIphone.text =@"";
    }
    
    //地址类型
  


        NSInteger cityType =(NSInteger)self.photosModel.cityModel.param.verify_type;
        if (cityType ) {
            
            switch (cityType) {
                case 1:
                    self.cityTypeStr.text =@"机关事业";
                    break;
                case 2:
                    self.cityTypeStr.text =@"企业员工";
                    break;
                default:
                    self.cityTypeStr.text =@"城镇居民";
                    break;
            }
            
            
        }
    //判断是否是异地或者本地
    self.yidiLabel.text =  [self panduanIsDifferentCountry];
    
    
    //地址

    
    if ([self.companyNew isEqualToString:@""]) {
        self.cityaddressStr.text =[NSString stringWithFormat:@"%@%@%@%@%@",
                                   [[NSUserDefaults standardUserDefaults]objectForKey:@"successProvinceKankan"],
                                   [[NSUserDefaults standardUserDefaults]objectForKey:@"successareaKankan"],
                                   [[NSUserDefaults standardUserDefaults]objectForKey:@"successdowntownKankan"],
                                   [[NSUserDefaults standardUserDefaults]objectForKey:@"successTownKankan"],
                                   [[NSUserDefaults standardUserDefaults]objectForKey:@"successDowntownKankan"]];
    }else{
        
        self.cityaddressStr.text =[NSString stringWithFormat:@"%@%@%@%@%@%@",
                                   [[NSUserDefaults standardUserDefaults]objectForKey:@"successProvinceKankan"],
                                   [[NSUserDefaults standardUserDefaults]objectForKey:@"successareaKankan"],
                                   [[NSUserDefaults standardUserDefaults]objectForKey:@"successdowntownKankan"],
                                   [[NSUserDefaults standardUserDefaults]objectForKey:@"successTownKankan"],
                                   [[NSUserDefaults standardUserDefaults]objectForKey:@"successDowntownKankan"],
        self.companyNew];
    }
    
    
    

    
    //测试代码
    self.title =@"参保信息";
    //雷俊博
//    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 configBackBtn];
    
    
    
    
  
    
    self.label_Big_One.textColor =kRGBColor(31, 157, 217);
    self.label_small_One.textColor =kRGBColor(31, 157, 217);
    
    
    //5.5 90 高度480
    //4.7 50 高度
    //4 30  高度 390
    //3.5  10  高度 350
    
    if ([UIScreen mainScreen].bounds.size.width == 375 ) {
        //4.7寸的手机
        self.leftTelIphone.constant  = 75;
    }else if ([UIScreen mainScreen].bounds.size.width == 320){
        //3.2寸 和4寸手机
        self.leftTelIphone.constant  = 65;
    }else if ([UIScreen mainScreen].bounds.size.width == 414){
        //5.5寸手机
        self.leftTelIphone.constant  = 85;
    }
    
    
    
    if ([[[UIDevice currentDevice]deviceModel] isEqualToString:Device_iPhone5S] || [[[UIDevice currentDevice]deviceModel] isEqualToString:Device_iPhone5] || [[[UIDevice currentDevice]deviceModel] isEqualToString:Device_iPhone5C]) {
        self.button_1.titleLabel.font =[UIFont systemFontOfSize:12];
         self.button_2.titleLabel.font =[UIFont systemFontOfSize:12];
         self.button_3.titleLabel.font =[UIFont systemFontOfSize:12];
 
    }
  if([[UIScreen mainScreen]bounds].size.height == 568)
  {
      self.button_1.titleLabel.font =[UIFont systemFontOfSize:13];
      self.button_2.titleLabel.font =[UIFont systemFontOfSize:13];
      self.button_3.titleLabel.font =[UIFont systemFontOfSize:13];
    
  }
    
    NSArray *radioArray = @[_button_1, _button_2, _button_3];
    for (int i=0; i<radioArray.count; ++i)
    {
        CLMarkButton *button = radioArray[i];
        button.type = CLMarkTypeSingleRadio;
        button.groupId = 10001;
        button.tag = i;
        [button addTarget:self action:@selector(buttonClick:) forControlEvents:UIControlEventTouchUpInside];
    }
    UIView *blankView = [[UIView alloc] initWithFrame:CGRectMake(_loactionText.frame.origin.x,_loactionText.frame.origin.y,5.0, _loactionText.frame.size.height)];
    
    _loactionText.leftView = blankView;
    
    _loactionText.leftViewMode =UITextFieldViewModeAlways;
    _loactionText.userInteractionEnabled =NO;
    self.cityCanSender =NO;
    self.hideView.hidden =NO;
    
    self.telIphone.delegate =self;
    
      [self layoutSize];
    //我在这里改了代码

    
      //V1.3.2关闭支付功能 多加了下面两行代码
    if ([getPeopleID getpeopleLimited] == YES) {
        self.isWaidi=NO;
        self.isWaidi_2=NO;
    }else{
        self.isWaidi_2 =NO;
        [self ufffblackground];
        self.ApplePayView.hidden  = YES;
        [self applePay];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(ageAchange:) name:@"KankanApplePay" object:nil];
        
    }
    
}
-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear: YES];
     [self.view closeKeyboardOffsetView];
//    [self.delegate returnViewController:self returnValue:self.showpickerPicture.image];
    if(self.modelCode != 0){
        self.navigationController.navigationBar.translucent = YES;
    }
    
    
   
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    // 禁用返回手势
    if ([self.navigationController respondsToSelector:@selector(interactivePopGestureRecognizer)]) {
        self.navigationController.interactivePopGestureRecognizer.enabled = NO;
    }
}



#pragma mark - 导航栏返回按钮及点击事件
- (void)configBackBtn
{
    UIButton *backbtn = [UIButton buttonWithType:UIButtonTypeCustom];
    backbtn.frame = CGRectMake(-50, 0, 40, 40);
    [backbtn setTitle:@"返回" forState:UIControlStateNormal];
    [backbtn setImage:[UIImage imageNamed:@"返回"] forState:UIControlStateNormal];
    [backbtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [backbtn addTarget:self action:@selector(backBtnClick:) forControlEvents:UIControlEventTouchUpInside];

    [backbtn layoutButtonWithEdgeInsetsStyle:GLButtonEdgeInsetsStyleLeft imageTitleSpace:6];

    

    
    UIBarButtonItem *backItem = [[UIBarButtonItem alloc]initWithCustomView:backbtn];

    self.navigationItem.leftBarButtonItem = backItem;
    
 
}

- (void)backBtnClick:(UIButton *)btn
{
//    BOOL show = [[NSUserDefaults standardUserDefaults]boolForKey:@"SocialSecurityAuthentication"];
//    if (!show) {
        [AuthenticationGuideView showGuideViewWithimgHidden:NO Block:^(BOOL isBack) {
           // [[NSUserDefaults standardUserDefaults]setBool:YES forKey:@"SocialSecurityAuthentication"];
           // [[NSUserDefaults standardUserDefaults]synchronize];
            if (isBack) {
                
                
                [self.navigationController popViewControllerAnimated:YES];
            }
        }];
   // }else {
//         [self.navigationController popViewControllerAnimated:YES];
//    }
    
    
    
}







//使用最简单的方法

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#define mark 照片代理方法

-(BOOL)textFieldShouldBeginEditing:(UITextField*)textField{
    
    
    return YES;
    
}



- (IBAction)sendToThePick:(UIButton*)sender {
    

    
    [self goToTheNetManagerBecausePhoto:sender];
}


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

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


#pragma mark - 访问相机的网络请求
-(void)goToTheNetManagerBecausePhoto:(UIButton*)sender
{//异地国外无法使用
    if (self.address_relation == 2) {
        SVProgressHUD.minimumDismissTimeInterval =2.0;
        [SVProgressHUD showErrorWithStatus:@"异地国外无法使用"];
        return;
    }else if(self.address_relation == 0)
    {
    

          [self senderAFnetMessage:sender];
    }else  if(self.address_relation == 1){

          [self senderAFnetMessage:sender];
    }
}
-(void)senderAFnetMessage:(UIButton*)button
{
    //v1.3.2注释了下面两行,下面的版本调整过来
    if ([self.telIphone.text length] != 11) {
        return [SVProgressHUD showErrorWithStatus:@"不是电话号码或请检查电话号码是否填写或有空格"];
    }
    
    
    
    if ([getPeopleID getpeopleLimited] ==NO) {
        if (_isWaidi == YES) {
            //支付的接口调用
            self.ApplePayView.hidden =NO;
            self.view_f.hidden = NO;
            [self.view bringSubviewToFront:self.ApplePayView];
            return;
        }
    }
    
        [SVProgressHUD shows];
    NSUserDefaults* userDefault=[NSUserDefaults standardUserDefaults];
    NSString *names =[userDefault objectForKey:@"name"];
    NSString *identifity =[userDefault objectForKey:@"identityNumber"];
    NSString *ID =[userDefault objectForKey:@"bak"];
    NSLog(@"ID:%@",ID);
    NSLog(@"cityCansneder:%d",self.cityCanSender);
    NSLog(@"placeMark:%@",_pMark);
    NSString *path =@"";
    path =[IPDIZHI stringByAppendingString:@"/socialsecurity/kankan/addressRelation"];
   [[NSUserDefaults standardUserDefaults]setValue:self.loactionText.text forKey:@"gdfdsgdfght"];
    [[NSUserDefaults standardUserDefaults]synchronize];
    
  
    
    
    [CityNetManager getaddressRelationToThePath:path getID:ID FortheName:names theIdentityNumberPara:identifity verifyType:self.address_relation nowAddress:self.loactionText.text andPhone:self.telIphone.text completionHandle:^(verifyAdressModel *model, NSError *error) {
         [SVProgressHUD doneShow];
        [SVProgressHUD dismiss];
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            //                调用摄像头的接口
            if(model.code != 0 || error.code != 0){
                SVProgressHUD.minimumDismissTimeInterval =2.0;
                [SVProgressHUD showErrorWithStatus:@"请检查网络情况"];
                return;
            }else{
                dispatch_async(dispatch_get_main_queue(), ^{

                    

                    
                    if (button == self.greenValue) {

                     self.gogreenValue =YES;
                        self.haokanView.hidden = NO;
                        [self.view addSubview:self.view_ff];
                        [self.view bringSubviewToFront:self.haokanView];
                    }else{


                        //一整套逻辑
                        LivenessViewController* dvc = [[LivenessViewController alloc] init];
                        dvc.delegate = self;
                        NSArray *array_ =nil;
//                        NSInteger kankanZhang =   [[NSUserDefaults standardUserDefaults]integerForKey:@"huoti_kankan_int"];
                        //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:0];
//                        __weak typeof(self) weakSelf = self;
                        /*dvc.completion = ^(NSDictionary *images, NSMutableArray *originImage) {


                            [weakSelf.imageManyImage removeAllObjects];

                            if (originImage.count == 0) {


                            }else{
                                //UIStoryboard *sb  =[UIStoryboard storyboardWithName:@"Main" bundle:nil];
                                [weakSelf.imageManyImage addObject:originImage[0]];
                                [weakSelf.imageManyImage addObject:originImage[originImage.count-3]];
                                [weakSelf.imageManyImage addObject:originImage[originImage.count-2]];
                                [weakSelf.imageManyImage addObject:originImage[originImage.count-1]];


                                        [weakSelf postmessageInToPhoto:originImage[0] and:nil];

                            }


                            //finish

                        };*/
                        [self presentViewController:dvc animated:YES completion:nil];
        
                    }
          
                    
                });
            }
        });
        [SVProgressHUD dismiss];
    }];

}


-(void)chooseButton
{
   
}
- (void)buttonClick:(CLMarkButton *)sender
{
    [sender buttonDidClick];
    
    if (sender == self.button_1) {

       // self.hideView.hidden =YES;
        self.middleImage.hidden =NO;
         self.cityCanSender =NO;
        self.label_Big_One.textColor =kRGBColor(31, 157, 217);
        self.label_small_One.textColor =kRGBColor(31, 157, 217);

        self.label_Big_Two.textColor =kRGBColor(94, 94, 102);
        self.label_Small_two.textColor =kRGBColor(197, 197, 197);
        self.label_Big_Three.textColor =kRGBColor(94, 94, 102);
        self.label_Small_Three.textColor =kRGBColor(197, 197, 197);
        [self locationView];
        
    }else if(sender ==self.button_2)
    {
      
        self.hideView.hidden =NO;
        self.cityCanSender =NO;
        self.label_Big_Two.textColor =kRGBColor(31, 157, 217);
        self.label_Small_two.textColor =kRGBColor(31, 157, 217);
        self.label_Big_One.textColor =kRGBColor(94, 94, 102);
        self.label_small_One.textColor =kRGBColor(197, 197, 197);

        self.label_Big_Three.textColor =kRGBColor(94, 94, 102);
        self.label_Small_Three.textColor =kRGBColor(197, 197, 197);
    
    }else if(sender ==self.button_3)
    {
    
        self.hideView.hidden =NO;
        self.cityCanSender =NO;
        self.label_Big_Three.textColor =kRGBColor(31, 157, 217);
        self.label_Small_Three.textColor =kRGBColor(31, 157, 217);
        self.label_Big_One.textColor =kRGBColor(94, 94, 102);
        self.label_small_One.textColor =kRGBColor(197, 197, 197);
        self.label_Big_Two.textColor =kRGBColor(94, 94, 102);
        self.label_Small_two.textColor =kRGBColor(197, 197, 197);

   
    }else
    {
      
    }
   
}

- (void)loadImageFinished:(UIImage *)image
{
    UIImageWriteToSavedPhotosAlbum(image, self, @selector(image:didFinishSavingWithError:contextInfo:), (__bridge void *)self);
    
}

- (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo
{
    
    NSLog(@"image = %@, error = %@, contextInfo = %@", image, error, contextInfo);
}


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

}

- (IBAction)ButtTag:(UIButton *)sender {


    
    switch (sender.tag) {
        case 8912:
    // 返回
            self.haokanView.hidden = YES;
            [self.view_ff removeFromSuperview];
            break;
        case 8913:
     // //继续
            [self jixu];
            break;
        default:
            break;
    }
    
    
    
    
    
}

-(void)jixu{
    if ([getPeopleID getpeopleLimited] ==NO) {
     
        if (_isWaidi == YES) {
            //支付的接口调用
            self.ApplePayView.hidden =NO;
            self.view_f.hidden = NO;
            [self.view bringSubviewToFront:self.ApplePayView];
            return;
        }
    }
    self.haokanView.hidden = YES;
    [self.view_ff removeFromSuperview];

    [self camerma];
}

//
#pragma mark - 普通相机逻辑


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

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

#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.imageManyImage removeAllObjects];
    
    [self.imageManyImage addObject:originImage[0]];
    [self.imageManyImage addObject:originImage[originImage.count-3]];
    [self.imageManyImage addObject:originImage[originImage.count-2]];
    [self.imageManyImage addObject:originImage[originImage.count-1]];


    [self postmessageInToPhoto:originImage[0] and:nil];
    
}

- (void)passFail {
    
}


-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
   
    //完成选择
    NSString *type = [info objectForKey:UIImagePickerControllerMediaType];
    if ([type isEqualToString:@"public.image"]) {
        __block UIImage *flippedImage = [info objectForKey:@"UIImagePickerControllerOriginalImage"];
        if (flippedImage == nil) {
            [SVProgressHUD showErrorWithStatus:@"请在设置中打开照片访问权限"];
            return;
        }
        
       /* flippedImage  = [UIImage imageWithCGImage:flippedImage.CGImage
                                            scale:1.0 orientation: UIImageOrientationLeftMirrored];*/
        dispatch_async(dispatch_get_main_queue(), ^{
            [picker dismissViewControllerAnimated:YES completion:^{
//                UIStoryboard *sb  =[UIStoryboard storyboardWithName:@"Main" bundle:nil];
//                SecondSocialViewController*bvc =[sb instantiateViewControllerWithIdentifier:@"SecondSocialViewController"];
//                bvc.image1  =flippedImage;
//                bvc.greenValues =@"绿色通道";
//                bvc.state = GreenRenZheng;
//                bvc.social =[socialSecurityViewController sharedInstance];
//                [self.navigationController pushViewController:bvc animated:YES];
                
                //雷俊博
                GreenChannelVC *vc = [[GreenChannelVC alloc]init];
                vc.title = @"绿色通道";
                vc.lastVCImage = flippedImage;
                vc.state = GreenRenZheng;
                vc.ValidationName = self.ValidationName;
                vc.ValidationIdNumber = self.ValidationIdNumber;
                vc.bak = self.bak;

                [self.navigationController pushViewController:vc animated:YES];
            }];
        });
    }
}
#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{
    NSUserDefaults* userDefault=[NSUserDefaults standardUserDefaults];
    //NSString *names =[userDefault objectForKey:@"name"];
    NSString *identifity =[userDefault objectForKey:@"identityNumber"];
    //支付接口
    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:identifity andList:self.product_no];
        
    }
    
}
-(void)laozuoJieKou{
    NSUserDefaults* userDefault=[NSUserDefaults standardUserDefaults];
    //NSString *names =[userDefault objectForKey:@"name"];
    NSString *identifity =[userDefault objectForKey:@"identityNumber"];
    //test
    __weak __typeof(self)weakSelf = self;
    //调用老左的接口获取数据
    [getAppleyPayGeogle getValidateIsOrNotPay:nil abd:identifity 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;
        }
        
        
    }];
    
    
}
- (IBAction)cloaseAll:(UIButton *)sender {
    
    switch (sender.tag) {
            
        case 9907:
            //关闭
            //  self.shareHide.hidden = YES;
            //            [self.view_f removeFromSuperview];
            
            [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)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"];获取产品的编号
    //********************************获取产品编号*********************
    
    //改百度的版本记得在pickerView 取这个值
    NSString *cityPay =   self.county;
    
    NSLog(@"%@",[getPeopleID applePaycity]);
    
    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.province isEqualToString:@"上海市"] || [weakSelf.province isEqualToString:@"北京市"] || [weakSelf.province isEqualToString:@"天津市"] || [weakSelf.province isEqualToString:@"重庆市"]){
//                if ([weakSelf.province isEqualToString:[getPeopleID applePaycity]]){
//                        NSLog(@"%@",weakSelf.province);
//                        NSLog(@"%@",[getPeopleID applePaycity]);
//                      weakSelf.isWaidi = NO;
//                }else{
//                    NSLog(@"%@",weakSelf.province);
//                    NSLog(@"%@",[getPeopleID applePaycity]);
//                    if ([getPeopleID getpeopleLimited] == YES ) {
//                        weakSelf.isWaidi = NO;
//
//                    }else{
//                      weakSelf.isWaidi = YES;
//                           [self laozuoJieKou];
//                    }
//
//
//                }
//            }else{
                NSLog(@"%@",cityPay);
                NSLog(@"%@",[getPeopleID applePaycity]);
                
                
                if ([cityPay isEqualToString:[getPeopleID applePaycity]]){
                    weakSelf.isWaidi = NO;
                }else{
                    
                    if ([getPeopleID getpeopleLimited] == YES  ) {
                        weakSelf.isWaidi = NO;
                        
                    }else{
                        if(!cityPay){
                             weakSelf.isWaidi = NO;
                        }else{
                            weakSelf.isWaidi = YES;
                            [self laozuoJieKou];
                        }

                    }
                    
                    

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

                        weakSelf.isWaidi = YES;
                        [self laozuoJieKou];
                    }
                    
                    
                    

                }
            }
//        }
    }
}


-(NSString*)panduanIsDifferentCountry{
       NSString *cityPay =   self.county;
    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:^{
      
            NSLog(@"%@",cityPay);
            NSLog(@"%@",[getPeopleID applePaycity]);
            
            
            if ([cityPay isEqualToString:[getPeopleID applePaycity]]){
                weakSelf.isDiffenentRegion = NO;
            }else{
                

                    if(!cityPay){
                        weakSelf.isDiffenentRegion = NO;
                    }else{
                        weakSelf.isDiffenentRegion = YES;
                       
                    }
                    
                
            }
        }];
    }else{


        if ([cityPay isEqualToString:[getPeopleID applePaycity]]){
            weakSelf.isDiffenentRegion = NO;//no
        }else{
                if(!cityPay){
                    weakSelf.isDiffenentRegion = NO;
                }else{
                    weakSelf.isDiffenentRegion = YES;
                }
            
        }
    

    }
    
    //**************新改的bug*************
    NSString *newBugSH= [getPeopleID applePaycity];
    if([MHSafeStrings(newBugSH) isEqualToString:@"上海市"] || [MHSafeStrings(newBugSH) isEqualToString:@"北京市"] || [MHSafeStrings(newBugSH) isEqualToString:@"天津市"] || [MHSafeStrings(newBugSH) isEqualToString:@"重庆市"]){
        if ([MHSafeStrings(self.province) isEqualToString:MHSafeStrings(newBugSH)]) {
            weakSelf.isDiffenentRegion = NO;
        }else{
            weakSelf.isDiffenentRegion = YES;

        }
        
        
    }
      //***************************
    
    
    if (weakSelf.isDiffenentRegion == YES) {
        self.address_relation =1;
        return @"异地-国内";
    }else{
         self.address_relation =0;
        return @"本地-国内";
    }
    
    
}




-(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 senderAFnetMessage:nil];
        
        }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)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"KankanApplePay" object:nil];
    
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
   
}
#pragma mark - 地址定位 目前使用到的只有后面两个方法
- (IBAction)LocationButton:(id)sender {
    self.gps = NO;
    [super viewWillAppear:YES];


    
    [[XWLocationManager sharedXWLocationManager] getCurrentLocation:^(CLLocation *location, CLPlacemark *placeMark, NSString *error) {
        if (error) {
            self.gps =NO;
            self.loactionText.text = MHSafeStrings(@"当前无法定位");
            NSLog(@"定位出错,错误信息:%@",error);
        }else{
            self.gps =YES;
            NSLog(@"定位成功:经度:%f 纬度:%lf 当前地址:%@  \n location详细信息:%@ \n ",location.coordinate.latitude, location.coordinate.longitude, placeMark.name, location);
            
            
            
            //            @property (nonatomic, readonly, copy, nullable) NSString *locality; // city, eg. Cupertino
            
            //            @property (nonatomic, readonly, copy, nullable) NSString *administrativeArea; // state, eg. CA
            //            @property (nonatomic, readonly, copy, nullable) NSString *subAdministrativeArea; // county, eg. Santa Clara
            //            @property (nonatomic, readonly, copy, nullable) NSString *postalCode; // zip code, eg. 95014
            //            @property (nonatomic, readonly, copy, nullable) NSString *ISOcountryCode; // eg. US
            //            @property (nonatomic, readonly, copy, nullable) NSString *country; // eg. United States
            //            @property (nonatomic, readonly, copy, nullable) NSString *inlandWater; // eg. Lake Tahoe
            //            @property (nonatomic, readonly, copy, nullable) NSString *ocean; // eg. Pacific Ocean
            //            @property (nonatomic, readonly, copy, nullable) NSArray<NSString *> *areasOfInterest; // eg. Golden Gate Park
            if([placeMark.locality isEqualToString:@"上海市"] || [placeMark.locality isEqualToString:@"北京市"] || [placeMark.locality isEqualToString:@"天津市"] || [placeMark.locality isEqualToString:@"重庆市"]){
                [self.loactionText setText:[NSString stringWithFormat:@"%@%@%@%@",
                                            MHSafeStrings(placeMark.country),
                                            MHSafeStrings(placeMark.locality),
                                            MHSafeStrings(placeMark.subLocality),
                                            //                                        MHSafeString(placeMark.thoroughfare),
                                            MHSafeStrings(placeMark.name)
                                            ]];
                  self.dizhi.text =self.loactionText.text;
            }else{
                
                NSDictionary *addressDic = placeMark.addressDictionary;
                NSString *state=[addressDic objectForKey:@"State"];
                NSString *city=[addressDic objectForKey:@"City"];
                NSString *subLocality=[addressDic objectForKey:@"SubLocality"];
                NSString *street=[addressDic objectForKey:@"Street"];
                
                
                
                [self.loactionText setText:[NSString stringWithFormat:@"%@%@%@%@",
                                            MHSafeStrings(state),
                                            MHSafeStrings(city),
                                            MHSafeStrings(subLocality),
                                            //                                        MHSafeString(placeMark.thoroughfare),
                                            MHSafeStrings(street)
                                            ]];
                
            }
              self.dizhi.text =self.loactionText.text;

            //这三个是有一些区别的,administrativeArea为null,subadministrativeArea也为null,如果老大说有错误,我就把adminstractiveAREA改成locality
            
            
            
            
            
            
            //获取城市
            NSString *city = placeMark.administrativeArea;
            //            if (!city) {
            //                //四大直辖市的城市信息无法通过locality获得，只能通过获取省份的方法来获得（如果city为空，则可知为直辖市）
            //                city = placeMark.;
            //            }
            //            [SVProgressHUD showSuccessWithStatus:city];
            
            
            NSLog(@"%@",placeMark.locality);
            NSLog(@"%@",placeMark.administrativeArea);
         
          
            
            
            
            
            _pMark =  [self.province stringByAppendingString:self.county];
            
            //判断是否gps开启
            
              NSLog(@"%@",placeMark.subLocality );
               NSLog(@"%@",city);
            NSLog(@"%@",self.province);
            NSLog(@"%@",self.city);
            if([city isEqualToString:self.province] || [placeMark.subLocality isEqualToString:self.city] )
            {
                self.cityCanSender =YES;
                NSLog(@"%d",self.cityCanSender);
                //判断gps 和 城市是一样的
                self.jb =YES;
            }
            if([city isEqualToString:self.city] && self.address_relation == 0)
            {
                self.cityCanSender =YES;
                NSLog(@"%d",self.cityCanSender);
            }else if(self.address_relation == 1 || self.address_relation == 2)
            {
                self.cityCanSender =YES;
            }else
            {
                NSLog(@"ss");
            }
        }
    } onViewController:self];
    
    
    
    
    
    
    
    //     NSString *address = ABCreateStringWithAddressDictionary(placeMark.addressDictionary, YES);
    ////            NSLog(@"%@",address);
    
    
}

-(void)locationView
{
    self.gps = NO;
    [super viewWillAppear:YES];
    
    [[XWLocationManager sharedXWLocationManager] getCurrentLocation:^(CLLocation *location, CLPlacemark *placeMark, NSString *error) {
        if (error) {
            self.gps =NO;
            self.loactionText.text = MHSafeStrings(@"当前无法定位");
              self.dizhi.text =self.loactionText.text;
            NSLog(@"定位出错,错误信息:%@",error);
        }else{
            self.gps =YES;
            NSLog(@"定位成功:经度:%f 纬度:%lf 当前地址:%@  \n location详细信息:%@ \n ",location.coordinate.latitude, location.coordinate.longitude, placeMark.name, location);
            


                NSDictionary *addressDic = placeMark.addressDictionary;
                NSString *state=[addressDic objectForKey:@"State"];
                NSString *city=[addressDic objectForKey:@"City"];
                NSString *subLocality=[addressDic objectForKey:@"SubLocality"];
                NSString *street=[addressDic objectForKey:@"Street"];
                [self.loactionText setText:[NSString stringWithFormat:@"%@%@%@%@",
                                            MHSafeStrings(state),
                                            MHSafeStrings(city),
                                            MHSafeStrings(subLocality),
                                            //                                        MHSafeString(placeMark.thoroughfare),
                                            MHSafeStrings(street)
                                            ]];
              self.dizhi.text =self.loactionText.text;
            
            _pMark =  [self.province stringByAppendingString:self.county];
            
            NSString *strNew =@"";
            if([self.province isEqualToString:@"上海市"] || [self.province isEqualToString:@"北京市"] || [self.province isEqualToString:@"天津市"] || [self.province isEqualToString:@"重庆市"]){
                strNew = self.province;
            }else{
                strNew = self.county;
            }
            if([MHSafeStrings(city) isEqualToString:strNew]) {//判断是否为本市的人
                self.cityCanSender =YES;
                NSLog(@"%d",self.cityCanSender);
                //判断gps 和 城市是一样的
                self.jb =YES;
            }

            
            
        }
    } onViewController:self];
}



-(void)postmessageInToPhoto:(UIImage *)selfImage and:(UIViewController*)vc
{
    
    //    [self senderManyPic];
    
    
    
    
    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 =@"";
   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);
    
    
    

    
    [SVProgressHUD shows];
    
    [self.baocun removeAllObjects];
    
    NSArray *dataArray =@[ [self imageChangeType:selfImage],
                           [self imageChangeType:self.imageManyImage[1]],
                           [self imageChangeType:self.imageManyImage[2]],
                           [self imageChangeType:self.imageManyImage[3]]];
    //        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;
            }
        }
    }
    
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
    [CityNetManager  getaddressPhotoToThePath:path getID:ID FortheName:names theIdentityNumberPara:identifity image:dateImage1 andPhone:nil andArray:self.baocun  completionHandle:^(verifyAdressModel *model, NSError *error) {
        [SVProgressHUD doneShow];
        [SVProgressHUD dismiss];
    
            
            if (error) {
                     dispatch_async(dispatch_get_main_queue(), ^{
                return [SVProgressHUD showErrorWithStatus:@"网络状态差无法继续下一步"];
                             });
            }
            
            
            
            if(model.code == 0)
            {
                
                //        [self  senderManyPic];
                
                
                
                dispatch_async(dispatch_get_main_queue(), ^{
                    [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];
                    
                    //雷俊博存储认证成功信息,在认证m页面显示
                    if (self.ValidationName) {
                        NSDictionary *ValidationDic = @{@"ValidationName":self.ValidationName};
                        [[NSUserDefaults standardUserDefaults]setObject:ValidationDic forKey:@"ValidationDic"];
                        [[NSUserDefaults standardUserDefaults]synchronize];
                        [getPeopleID getprovinceNightSix:self.province];
                    }
                   
                    
                });

            }else{
      
            
                  dispatch_async(dispatch_get_main_queue(), ^{
            
            
            
            UIStoryboard *sb  =[UIStoryboard storyboardWithName:@"Main" bundle:nil];
            MyPickerViewController *picker =[sb instantiateViewControllerWithIdentifier:@"MyPickerViewController"];
            picker.arrayImages =self.imageManyImage;
            picker.province =self.province;
            picker.city =self.city;
            picker.county =self.county;
            picker.telPhone =self.telIphone.text;
                picker.modelCode = model.code;
                self.modelCode =model.code;
            if (self.gogreenValue == YES) {
                picker.greenValues =@"绿色通道";
            }else{
                picker.greenValues =@"";
            }
            
            [self.navigationController pushViewController:picker animated:YES];
            
              });
            }
          
        
            
            
      
        
        
    }];
     });
    
}

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    if ([segue.identifier isEqualToString:@"successSegue"])  {
        
        [getPeopleID socialSate:1];
        [[NSNotificationCenter defaultCenter] postNotificationName:@"ZLAuthenticationAssistant" object:nil userInfo:nil];
        
        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;
        blueVC.name = self.ValidationName;
        blueVC.idNumber = self.ValidationIdNumber;
        blueVC.bak = self.bak;
        
    }
}


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

-(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);
    
    NSString *str3=[EnercryTool encryptBase64:dateImage1];
    return str3;
    
}

-(void)jiantingKeyBoard
{
    
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
    
    
}

#pragma mark ---- 根据键盘高度将当前视图向上滚动同样高度
///键盘显示事件
- (void)keyboardWillShow:(NSNotification *)notification {
    //获取键盘高度，在不同设备上，以及中英文下是不同的
    CGFloat kbHeight = [[notification.userInfo objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue].size.height;
    
    //计算出键盘顶端到inputTextView panel底端的距离(加上自定义的缓冲距离INTERVAL_KEYBOARD)
    CGFloat offset = kbHeight;
    
    // 取得键盘的动画时间，这样可以在视图上移的时候更连贯
    double duration = [[notification.userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey] doubleValue];
    
    //将视图上移计算好的偏移
    if(offset > 0) {
        [UIView animateWithDuration:duration animations:^{
            self.view.frame = CGRectMake(0.0f, -offset+100, self.view.frame.size.width, self.view.frame.size.height);
        }];
    }
}

#pragma mark ---- 当键盘消失后，视图需要恢复原状
///键盘消失事件
- (void)keyboardWillHide:(NSNotification *)notify {
    // 键盘动画时间
    double duration = [[notify.userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey] doubleValue];
    //视图下沉恢复原状
    [UIView animateWithDuration:duration animations:^{
        self.view.frame = CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height);
    }];
}


@end
