//
//  CommitIDInfoController.m
//  KKCivilAd
//
//  Created by 雷俊博 on 2019/12/10.
//  Copyright © 2019 雷俊博. All rights reserved.
//

#import "CommitIDInfoController.h"
//#import "JYBDIDCardVC.h"
#import "UIImage+Custom.h"
#import "AuthenticationReviewController.h"

#import "Globaltypedef.h"
#if TARGET_IPHONE_SIMULATOR == 0
#import "SCCaptureCameraController.h"
#endif

@interface CommitIDInfoController ()
#if TARGET_IPHONE_SIMULATOR == 0
   <UINavigationControllerDelegate,UIImagePickerControllerDelegate,SCNavigationControllerDelegate>
#endif
{
    NSString *frontImgBase64Str;
    NSString *backImgBase64Str;
    UIView*tapView;
}

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

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

@property (weak, nonatomic) IBOutlet UIImageView *img_IdFront;
@property (weak, nonatomic) IBOutlet UIImageView *img_IdBack;

@property (weak, nonatomic) IBOutlet UIButton *leftBtn;
@property (weak, nonatomic) IBOutlet UIButton *rightBtn;


@end

@implementation CommitIDInfoController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self configUI];
}

- (void)configUI
{
    
    
    
    [self addTapGesture:_leftView];
    [self addTapGesture:_rightView];
    [self addDashLineView:_leftView];
    [self addDashLineView:_rightView];
    
    [self.leftBtn setImageEdgeInsets:UIEdgeInsetsMake(15, 0, 15, 0)];

    self.leftBtn.imageView.contentMode = UIViewContentModeScaleAspectFill;

    
}
- (void)addTapGesture:(UIView *)view
{
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(scanIdCard:)];
    
    [view addGestureRecognizer:tap];
}

- (void)addDashLineView:(UIView *)view
{
    UIBezierPath *maskPath=[[UIBezierPath bezierPathWithRoundedRect:view.bounds byRoundingCorners:UIRectCornerAllCorners cornerRadii:CGSizeMake(10, 10)] bezierPathByReversingPath];
    CAShapeLayer *border = [CAShapeLayer layer];
    // 线条颜色
    border.strokeColor = [UIColor colorWithHex:0xdcdcdc].CGColor;
    border.masksToBounds = YES;

    border.fillColor = nil;
    border.path = maskPath.CGPath;
    border.frame = view.bounds;

    border.lineWidth = 1;
    border.lineCap = @"square";
    // 第一个是 线条长度 第二个是间距 nil时为实线
    border.lineDashPattern = @[@4, @2];
    [view.layer addSublayer:border];
   
}


#pragma mark - load api
- (NSDictionary *)requestParams
{
    NSDictionary *para = @{
        @"idcardFront":frontImgBase64Str,
        @"idcardBack":backImgBase64Str,
        @"recordId":self.recordId
    };
    return para;
}

- (void)uploadDataRequest
{
    if ([self.type isEqualToString:@"butie"]) {
        [self butieUploadDataRequest];
    }else{
        [self youfuUploadDataRequest];
    }
}

- (void)youfuUploadDataRequest
{
    WeakSelf
       NSString *urlString = [NSString stringWithFormat:@"%@%@",[NetworkConfig ipYouFuVerityConfig],UpLoadIDCardInfoRequest];
       NSLog(@"提交身份证信息url%@",urlString);
       NSLog(@"prams:%@",[self requestParams]);
       NSString *token = [UserDefault objectForKey:@"token"];
       
       [SVProgressHUD show];
       [NetworkRequest Post3:urlString Params:[self requestParams] Token:token Success:^(id  _Nonnull responseObject) {
           [SVProgressHUD dismiss];
           NSLog(@"responseObject:%@",responseObject);
           if ([responseObject isKindOfClass:[NSDictionary class]]) {
               NSString *state = [NSString stringWithFormat:@"%@",responseObject[@"state"]];
               if ([state isEqualToString:@"200"]) {
                  
                   AuthenticationReviewController *vc = [Storyboard instantiateViewControllerWithIdentifier:@"AuthenticationReviewController"];
                   vc.title = @"认证完成";
                   [self.navigationController pushViewController:vc animated:YES];
                   
               }else if ([state isEqualToString:@"700"]){
                   [weakSelf reloadData];
               }else{
                   [self alertShow:@"上传失败"];
               }
               
           }else{
               [self alertShow:@"服务器异常"];
           }
           
           
       } Failure:^(NSError * _Nonnull error) {
           [SVProgressHUD dismiss];
           NSLog(@"error:%@",error);
           [self alertShow:@"网络异常"];
       }];
}

- (void)butieUploadDataRequest{
    WeakSelf
       NSString *urlString = [NSString stringWithFormat:@"%@%@",[NetworkConfig ipYouFuVerityConfig],UpLoadIDCardInfoRequest];
       NSLog(@"提交身份证信息url%@",urlString);
       NSLog(@"prams:%@",[self requestParams]);
       NSString *token = [UserDefault objectForKey:@"token"];
       
       [SVProgressHUD show];
       [NetworkRequest Post7:urlString Params:[self requestParams] Token:token Success:^(id  _Nonnull responseObject) {
           [SVProgressHUD dismiss];
           NSLog(@"responseObject:%@",responseObject);
           if ([responseObject isKindOfClass:[NSDictionary class]]) {
               NSString *state = [NSString stringWithFormat:@"%@",responseObject[@"state"]];
               if ([state isEqualToString:@"200"]) {
                  
                   AuthenticationReviewController *vc = [Storyboard instantiateViewControllerWithIdentifier:@"AuthenticationReviewController"];
                   vc.title = @"认证完成";
                   [self.navigationController pushViewController:vc animated:YES];
                   
               }else if ([state isEqualToString:@"700"]){
                   [weakSelf reloadData];
               }else{
                   [self alertShow:@"上传失败"];
               }
               
           }else{
               [self alertShow:@"服务器异常"];
           }
           
           
       } Failure:^(NSError * _Nonnull error) {
           [SVProgressHUD dismiss];
           NSLog(@"error:%@",error);
           [self alertShow:@"网络异常"];
       }];
}


- (void)reloadData
{
    WeakSelf
    [NetworkTokenRequest getTokenSuccess:^(BOOL success) {
        if (success) {
            [weakSelf uploadDataRequest];
        }else{
            [self alertShow:@"请求失败"];
        }
    }];
}


#pragma mark - 启动ocr
- (void)startOCR
{
    
    #if TARGET_IPHONE_SIMULATOR == 0
    SCCaptureCameraController*con = [[SCCaptureCameraController alloc] init];
    con.scNaigationDelegate = self;
    con.iCardType = TIDCARD2 ; // 其他证件以此类推
    con.isDisPlayTxt = NO;
    con.ScanMode = TIDC_SCAN_MODE;
    con.modalPresentationStyle = UIModalPresentationFullScreen;
    [self presentViewController:con animated:YES completion:NULL];
    #endif
    
}


#pragma mark - SCNavigationControllerDelegate
- (void)sendTakeImage:(TCARD_TYPE) iCardType image:(UIImage *)cardImage
{
    if (iCardType == TIDCARD2) {
        
        if (tapView == self.rightView) {
            
            [SVProgressHUD showErrorWithStatus:@"请拍摄身份证背面照"];
            return;
        }
        
        if (tapView == self.leftView && cardImage ) {
               UIImage *newImage = [UIImage imageWithImage:cardImage scale:0.5];
               
               self.img_IdFront.image = newImage;
               NSData * imageData = UIImageJPEGRepresentation(newImage,1);
               NSLog(@" width =%f  height=%f  内存:%zu",newImage.size.width,newImage.size.height,[imageData length]/1024);
               self->frontImgBase64Str = [imageData base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength];
           }
    }else if (iCardType == TIDCARDBACK){
        
        if (tapView == self.leftView) {
            [SVProgressHUD showErrorWithStatus:@"请拍摄身份证正面照"];
            return;
        }
        
        if (tapView == self.rightView && cardImage){
               UIImage *newImage = [UIImage imageWithImage:cardImage scale:0.5];
               self.img_IdBack.image = newImage;
               NSData * imageData = UIImageJPEGRepresentation(newImage,1);
               NSLog(@" width =%f  height=%f  内存:%zu",newImage.size.width,newImage.size.height,[imageData length]/1024);
               self->backImgBase64Str = [imageData base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength];
           }
    }
   
    
}




#pragma mark - event response
- (void)scanIdCard:(UITapGestureRecognizer *)tap
{
    tapView = tap.view;
    
    [self startOCR];
}
- (IBAction)CommitClick:(UIButton *)sender {
    if (!frontImgBase64Str) {
        [self alertShow:@"请拍摄身份证正面照片"];
        return;
    }else if (!backImgBase64Str){
        [self alertShow:@"请拍摄身份证背面照片"];
        return;
    }
    
    [self uploadDataRequest];
    
}



- (void)alertShow:(NSString *)msg
{
    if (@available(iOS 9.0,*)) {
        
        UIAlertController * alertV = [UIAlertController alertControllerWithTitle:@"提示" message:msg preferredStyle:UIAlertControllerStyleAlert];
        
        UIAlertAction *confirm = [UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            
        }];
        
        [alertV addAction:confirm];
        
        [self presentViewController:alertV animated:YES completion:nil];
        
    }else{
        UIAlertView *alertV = [[UIAlertView alloc]initWithTitle:@"提示" message:msg delegate:nil cancelButtonTitle:@"确定" otherButtonTitles: nil];
        [alertV show];
    }
}


/*
#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
