//
//  regardTableViewController.m
//  Open
//
//  Created by 看看智能 on 2017/2/28.
//  Copyright © 2017年 黄江涛 . All rights reserved.
//

#import "KKUserImageViewController.h"
#import "VoucherRecordViewController.h"
#import "introduceViewController.h"
#import "SDCycleScrollView.h"
#import "NewEditionTestManager.h"


#import "VersionUpdateTool.h"
@interface KKUserImageViewController ()<SCNavigationControllerDelegate>

@property(nonatomic,strong)UIImageView *frontImage;
@property(nonatomic,strong)UIImageView *backImage;
@property(nonatomic)bool OcrOk;
@property(nonatomic,strong)NSString *vaildPeriod;
@property(nonatomic,strong)NSString *ossFrontPath;
@property(nonatomic,strong)NSString *ossBackPath;
@end

@implementation KKUserImageViewController

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self.navigationController.navigationBar navBarBackGroundColor:K_MainColor image:nil isOpaque:YES];//颜色
    [self.navigationController setNavigationBarHidden:NO animated:animated];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor =[UIColor colorWithRed:238/255.0 green:238/255.0 blue:238/255.0 alpha:1.0];
    self.title= @"证件上传";
    
    //底部按钮
    UIButton*confirmBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [confirmBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    confirmBtn.titleLabel.font = [UIFont systemFontOfSize:15*WIDTHRADIU];
    confirmBtn.backgroundColor = K_MainColor;
    [confirmBtn setTitle:@"确认上传" forState:UIControlStateNormal];
    [confirmBtn addTarget:self action:@selector(confirmBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:confirmBtn];
    [confirmBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.bottom.right.offset(0);
        make.height.offset(45 * WIDTHRADIU);
    }];
    
    UILabel* topTip = [UILabel new];
    topTip.text = @"上传本人身份证正反照";
    topTip.textColor = [UIColor colorWithHex:0x4c4c4c];
    topTip.font = [UIFont systemFontOfSize:17 * WIDTHRADIU];
    [self.view addSubview:topTip];
    [topTip mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.offset(cl_kNavigationBarHeight+10*WIDTHRADIU);
        make.left.offset(15*WIDTHRADIU);
    }];
    
    UILabel* topTip2 = [UILabel new];
    topTip2.text = @"提示:目前仅支持二代身份证原件申请";
    topTip2.textColor = [UIColor colorWithHex:0x9c9c9c];
    topTip2.font = [UIFont systemFontOfSize:14 * WIDTHRADIU];
    [self.view addSubview:topTip2];
    [topTip2 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(topTip.mas_bottom).offset(5*WIDTHRADIU);
        make.left.offset(15*WIDTHRADIU);
    }];
    
    UIImageView* frontImage = [UIImageView new];
    [frontImage setImage:[UIImage imageNamed:@"up_load_front_bkg"]];
    frontImage.backgroundColor = [UIColor clearColor];
    frontImage.userInteractionEnabled=YES;
    UITapGestureRecognizer *front = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(frontClick:)];
    [frontImage addGestureRecognizer:front];
    [self.view addSubview:frontImage];
    [frontImage mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.view);
        make.top.equalTo(topTip2.mas_bottom).offset(10*WIDTHRADIU);
        make.width.offset(ScreenWidth-130*WIDTHRADIU);
        make.height.offset(ScreenWidth/20*9);
    }];
    self.frontImage=frontImage;
    
    UIImageView* backImage = [UIImageView new];
    [backImage setImage:[UIImage imageNamed:@"up_load_back_bkg"]];
    backImage.backgroundColor = [UIColor clearColor];
    backImage.userInteractionEnabled=YES;
    UITapGestureRecognizer *back = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(backClick:)];
    [backImage addGestureRecognizer:back];
    [self.view addSubview:backImage];
    [backImage mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.view);
        make.top.equalTo(frontImage.mas_bottom).offset(8*WIDTHRADIU);
        make.width.offset(ScreenWidth-130*WIDTHRADIU);
        make.height.offset(ScreenWidth/20*9);
    }];
    self.backImage=backImage;
    
    UIImageView* image01 = [UIImageView new];
    [image01 setImage:[UIImage imageNamed:@"ocr_attention_01"]];
    image01.backgroundColor = [UIColor clearColor];
    [self.view addSubview:image01];
    [image01 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(confirmBtn.mas_top).offset(-10*WIDTHRADIU);
        make.left.offset(15*WIDTHRADIU);
        make.width.offset((ScreenWidth-60*WIDTHRADIU)/4);
        make.height.offset(80*WIDTHRADIU);
    }];
    
    UIImageView* image02 = [UIImageView new];
    [image02 setImage:[UIImage imageNamed:@"ocr_attention_02"]];
    image02.backgroundColor = [UIColor clearColor];
    [self.view addSubview:image02];
    [image02 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(confirmBtn.mas_top).offset(-10*WIDTHRADIU);
        make.left.equalTo(image01.mas_right).offset(15*WIDTHRADIU);
        make.width.offset((ScreenWidth-60*WIDTHRADIU)/4);
        make.height.offset(80*WIDTHRADIU);
    }];
    
    UIImageView* image03 = [UIImageView new];
    [image03 setImage:[UIImage imageNamed:@"ocr_attention_03"]];
    image03.backgroundColor = [UIColor clearColor];
    [self.view addSubview:image03];
    [image03 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(confirmBtn.mas_top).offset(-10*WIDTHRADIU);
        make.left.equalTo(image02.mas_right).offset(15*WIDTHRADIU);
        make.width.offset((ScreenWidth-75*WIDTHRADIU)/4);
        make.height.offset(80*WIDTHRADIU);
    }];
    
    UIImageView* image04 = [UIImageView new];
    [image04 setImage:[UIImage imageNamed:@"ocr_attention_04"]];
    image04.backgroundColor = [UIColor clearColor];
    [self.view addSubview:image04];
    [image04 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(confirmBtn.mas_top).offset(-10*WIDTHRADIU);
        make.left.equalTo(image03.mas_right).offset(15*WIDTHRADIU);
        make.width.offset((ScreenWidth-75*WIDTHRADIU)/4);
        make.height.offset(80*WIDTHRADIU);
    }];
    
    UILabel* ocrTip = [UILabel new];
    ocrTip.text = @"拍摄时请注意";
    ocrTip.textColor = [UIColor colorWithHex:0x4c4c4c];
    ocrTip.font = [UIFont systemFontOfSize:15 * WIDTHRADIU];
    [self.view addSubview:ocrTip];
    [ocrTip mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(image01.mas_top).offset(-5*WIDTHRADIU);
        make.left.offset(15*WIDTHRADIU);
    }];
    
}

//图片上传
- (void)confirmBtnClick:(UIButton *)sender {
    NSLog(@"图片上传");
    if(self.ossBackPath==nil||[self.ossBackPath isEqualToString:@""]||[self.ossBackPath isEqual:[NSNull null]]){
        [Tools showMessage:@"请拍摄背面国徽照!"];
        return;
    }
    if(self.ossFrontPath==nil||[self.ossFrontPath isEqualToString:@""]||[self.ossFrontPath isEqual:[NSNull null]]){
        [Tools showMessage:@"请拍摄身份证正面照!"];
        return;
    }
    NSString *requset=[NSString stringWithFormat:@"%@%@",CSL_url,@"/auth/update/extra/info"];
    NSDictionary* front = @{
        @"vaildPeriod":self.vaildPeriod,
        @"idCardPositive":self.ossFrontPath,
        @"idCardReverse":self.ossBackPath,
        @"loginId":@([getPeopleID PeopleID]),
        @"loginTel":[getPeopleID PeopleIphoneNmber]
    };
    [NetworkRequest Post15:requset Params:front Success:^(id _Nonnull obj) {
        NSString *state=[NSString stringWithFormat:@"%@",obj[@"state"]];
        if([state isEqualToString:@"200"]){
            [self.delegate KKUserCompleteUp];
            [Tools showMessage:@"上传成功"];
            [self.navigationController popViewControllerAnimated:YES];
        }else{
            [Tools showMessage:obj[@"describe"]];
        }
    } Failure:^(NSError *error) {
        NSLog(@"上传网络错误:%@",error);
    }];
}
-(void)frontClick:(UITapGestureRecognizer *)tap{
    NSLog(@"前面....");
    SCCaptureCameraController *con = [[SCCaptureCameraController alloc] init];
    con.scNaigationDelegate = self;
    con.iCardType = TIDCARD2;
    con.isDisPlayTxt = NO;
    //con.TimeKey = TimeKeyS;
    con.ScanMode = TIDC_SCAN_MODE;
    [self presentViewController:con animated:YES completion:NULL];
    
}
-(void)backClick:(UITapGestureRecognizer *)tap{
    NSLog(@"后面....");
    SCCaptureCameraController *con = [[SCCaptureCameraController alloc] init];
    con.scNaigationDelegate = self;
    con.iCardType = TIDCARD2;
    con.isDisPlayTxt = NO;
    //con.TimeKey = TimeKeyS;
    con.ScanMode = TIDC_SCAN_MODE;
    [self presentViewController:con animated:YES completion:NULL];
}

//ocr图片回调
#pragma mark - SCNavigationControllerDelegate
- (void)sendAllValue:(NSString *)text{
    NSLog(@"all  = %@",text);
}

- (void)sendIDCValue:(NSString *)name SEX:(NSString *)sex FOLK:(NSString *)folk BIRTHDAY:(NSString *)birthday ADDRESS:(NSString *) address NUM:(NSString *)num{
    if (![IDCardNumber_Validate isValidateIDCardString:num]) {
        [SVProgressHUD showInfoWithStatus:@"身份证号识别错误,请重新拍摄"];
        _OcrOk=NO;
        return;
    }
    if(name==nil||[name isEqualToString:@""]){
        [SVProgressHUD showInfoWithStatus:@"姓名识别错误,请重新拍摄"];
        _OcrOk=NO;
        return;
    }

    _OcrOk=YES;
}

 - (void)sendIDCBackValue:(NSString *)issue PERIOD:(NSString *) period  IDCPASSNUM:(NSString *)passnum{
    NSLog(@"idcback  = %@%@",issue,period);
     if(period==nil||[period isEqualToString:@""]){
         [SVProgressHUD showInfoWithStatus:@"国徽面识别错误,请重新拍摄"];
         _OcrOk=NO;
         return;
     }
     self.vaildPeriod=period;
     _OcrOk=YES;
}

- (void)sendTakeImage:(TCARD_TYPE) iCardType image:(UIImage *)cardImage{
    NSLog(@"sendTakeImage = %d %@\n",iCardType,cardImage);
    NSData *small =UIImageJPEGRepresentation([self imageByScalingAndCroppingForSize:CGSizeMake(667, 375) and:cardImage], 1.0);
    NSString *ocrBase64 = [small base64EncodedStringWithOptions:0];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.7 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
       // 在延迟1秒后执行代码
        if(self.OcrOk){
            NSString *requset=[NSString stringWithFormat:@"%@%@",CSL_url,@"/file/upload/image"];
            if(iCardType==TIDCARD2){//上传正面
                NSDictionary* front = @{
                    @"fileBase64":ocrBase64,
                    @"key":@"idcard"
                };
                [NetworkRequest Post15:requset Params:front Success:^(id _Nonnull obj) {
                    NSString *state=[NSString stringWithFormat:@"%@",obj[@"state"]];
                    if([state isEqualToString:@"200"]){
                        self.ossFrontPath=obj[@"result"];
                        [self.frontImage sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",KKFindPackageIP,self.ossFrontPath]]];
                    }else{
                        [Tools showMessage:obj[@"describe"]];
                    }
                } Failure:^(NSError *error) {
                    NSLog(@"网络错误:%@",error);
                }];
                
            }else if (iCardType==TIDCARDBACK){
                NSDictionary* back = @{
                    @"fileBase64":ocrBase64,
                    @"key":@"idcard"
                };
                [NetworkRequest Post15:requset Params:back Success:^(id _Nonnull obj) {
                    NSString *state=[NSString stringWithFormat:@"%@",obj[@"state"]];
                    if([state isEqualToString:@"200"]){
                        self.ossBackPath=obj[@"result"];
                        [self.backImage sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",KKFindPackageIP,self.ossBackPath]]];
                    }else{
                        [Tools showMessage:obj[@"describe"]];
                    }
                } Failure:^(NSError *error) {
                    NSLog(@"网络错误:%@",error);
                }];
            }
        }
    });
}

- (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;
        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(targetSize);
    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)
    
 
    UIGraphicsEndImageContext();
    return newImage;
}
@end
