//
//  TestViewController.m
//  Open
//
//  Created by 雷俊博 on 2020/4/9.
//  Copyright © 2020 黄江涛 . All rights reserved.
//

#import "TestViewController.h"
#import "NetworkRequest.h"
#import "UIImage+Custom.h"
#import "UIImageView+WebCache.h"

@interface TestViewController ()<UIImagePickerControllerDelegate,UINavigationControllerDelegate>
{
    NSString* imageBase64Str;
}

@property (nonatomic, strong)UIImagePickerController *imagePicker;


@end

@implementation TestViewController

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:NO animated:animated];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    
    self.img1.image = self.originImage[0];
    self.img2.image = self.originImage[1];
    self.img3.image = self.originImage[2];
    self.img4.image = self.originImage[3];
    
    
    UITapGestureRecognizer* tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapClick)];

    [self.img1 addGestureRecognizer:tap];
    
    
    
}

- (void)tapClick
{
    [self getPhoto];
}


- (IBAction)btnClick:(UIButton *)sender {
    
   
      
      [self getTokenRequest:^(bool success, NSString *token) {
          if (success) {
              [self getIDPhoto:token];
          }
      }];
}


- (void)getPhoto
{
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"请选择获取图片操作" message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    // 使用前置还是后置摄像头
    
//    UIAlertAction *photos = [UIAlertAction actionWithTitle:@"从相册中" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
//        self.imagePicker.sourceType=UIImagePickerControllerSourceTypePhotoLibrary;
//        [self presentViewController:self.imagePicker animated:YES completion:nil];
//        
//    }];
    UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        
    }];
    
    UIAlertAction *makePhotos = [UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        self.imagePicker.sourceType=UIImagePickerControllerSourceTypeCamera;
        self.imagePicker.cameraDevice = UIImagePickerControllerCameraDeviceFront;
        [self presentViewController: self.imagePicker animated:YES completion:nil];
     
    }];
    //[alert addAction:photos];
    [alert addAction:makePhotos];
    [alert addAction:cancel];
    
    [self presentViewController:alert animated:YES completion:^{
        
    }];
}


- (NSDictionary *)getTokenRequestPara
{
    NSDictionary*params = @{
        @"loginId":[NSNumber numberWithInteger:[getPeopleID PeopleID]],
        @"telephone":[getPeopleID PeopleIphoneNmber]
    };
    return params;
}
- (void)getTokenRequest:(void (^)(bool success, NSString*token))response
{
//    NSString *soapStr = @"kankan-server";
    //NSString*url = @"http://test4.weface.com.cn/token";
    NSString *url = @"http://h5.weface.com.cn/renshe/user/token";
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    // 返回NSData
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    // 这个设置是必须的
//   [manager.requestSerializer setValue:@"text/xml; charset=utf-8" forHTTPHeaderField:@"Content-Type"];
//   // 设置HTTPBody
//   [manager.requestSerializer setQueryStringSerializationWithBlock:^NSString *(NSURLRequest *request, NSDictionary *parameters, NSError *__autoreleasing *error){
//        return soapStr;
//    }];
    [manager GET:url parameters:[self getTokenRequestPara] headers:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSDictionary *dicRes = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
        NSLog(@"JSON: - %@", dicRes);
        response(YES,dicRes[@"result"]);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        response(NO,nil);
    }];
}

- (NSDictionary *)getIDPhotoParams
{
    NSDictionary*params = @{
        @"idCard":[EnercryTool A:@"340826199712224421"]
    };
    return params;
}

- (void)getIDPhoto:(NSString *)token
{
   // NSString *url = @"http://test4.weface.com.cn/face/id_photo_base64";
    NSString*url = @"http://h5.weface.com.cn/20200513/zjz/query";
    
    [NetworkRequest Post5:url Params:[self getIDPhotoParams] Token:token Success:^(id  _Nonnull responseObject) {
         NSLog(@"responseObject:%@",responseObject);
        NSString*state = [NSString stringWithFormat:@"%@",responseObject[@"state"]];
        if ([state isEqualToString:@"200"]) {
            NSString*result = responseObject[@"result"];
            [self.img2 sd_setImageWithURL:[NSURL URLWithString:result]];
        }
    } Failure:^(NSError * _Nonnull error) {
       NSLog(@"error:%@",error);
    }];
    
}






#pragma mark - UIImagePickerControllerDelegate
- (void)imagePickerController: (UIImagePickerController *)picker
didFinishPickingMediaWithInfo: (NSDictionary *)info
{
    
    dispatch_async(dispatch_get_main_queue(), ^{
        UIImage *image = [info objectForKey:@"UIImagePickerControllerOriginalImage"];
        
        image = [UIImage imageWithImage:image scale:0.1];
        self.img1.image = image;
        NSData* imageData = UIImageJPEGRepresentation(image, 0.4);
        NSLog(@"%ldkb",imageData.length/1024);
        self->imageBase64Str = [imageData base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength];
        [self dismissViewControllerAnimated:YES completion:nil];
    });
  
}

// 用户选择取消
- (void) imagePickerControllerDidCancel: (UIImagePickerController *)picker
{
   [self dismissViewControllerAnimated:YES completion:nil];
   
}


#pragma mark - getters and setters
- (UIImagePickerController *)imagePicker
{
    if (!_imagePicker) {
        _imagePicker = [[UIImagePickerController alloc]init];
        _imagePicker.delegate = self;
        _imagePicker.allowsEditing = YES;
        
        
    }
    
    return _imagePicker;
}


/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
