//
//  KKPictureEditVC.m
//  Open
//
//  Created by qxy on 2021/10/13.
//  Copyright © 2021 QXY. All rights reserved.
//

#import "KKPictureEditVC.h"

@interface KKPictureEditVC ()<UINavigationControllerDelegate,UIImagePickerControllerDelegate>
@property (weak, nonatomic) IBOutlet UIImageView *BaseImgView;
@property (weak, nonatomic) IBOutlet UIView *WhiteningView;//美白视图
@property (weak, nonatomic) IBOutlet UIView *SaveView;//底部保存视图
@property (weak, nonatomic) IBOutlet UIView *baseColorView;
@property (weak, nonatomic) IBOutlet UISlider *SliderView;
@property (weak, nonatomic) IBOutlet UIButton *OneSizeBtn;
@property (nonatomic, assign) NSInteger Sizeindex; //图片尺寸
@property (nonatomic, assign) NSInteger bg_colorindex; //背景颜色
@property (nonatomic, strong)UIButton *selectSizeBtn;
@end

@implementation KKPictureEditVC
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];

    [self.navigationController setNavigationBarHidden:YES];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.

    [self navConfig];
    
    //初始化
    self.Sizeindex = 1;
    
    self.bg_colorindex = 0;
    
    self.selectSizeBtn = self.OneSizeBtn;
    
    self.SliderView.minimumValue = 0;
    self.SliderView.maximumValue = 1;
    self.SliderView.value = 0.5; //设置默认值
    
    self.BaseImgView.image = self.image;
    
    [self updatePhoto];
}
- (void)navConfig
{
    UIView*navView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, cl_kNavigationBarHeight)];
    navView.backgroundColor = [UIColor whiteColor];
    //返回按钮
    UIButton* backBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [backBtn setTitle:@"返回" forState:UIControlStateNormal];
    [backBtn setImage:[UIImage imageNamed:@"blackBack"] forState:UIControlStateNormal];
    [backBtn setTitleColor:[UIColor colorWithHex:0x4d4d4d] forState:UIControlStateNormal];
    backBtn.frame = CGRectMake(10, cl_kStatusBarHeight, 60, 44);
    backBtn.titleLabel.font = [UIFont systemFontOfSize:16];
    [backBtn layoutButtonWithEdgeInsetsStyle:GLButtonEdgeInsetsStyleLeft imageTitleSpace:4];
    [backBtn addTarget:self action:@selector(backClick:) forControlEvents:UIControlEventTouchUpInside];
    [navView addSubview:backBtn];
    
    UILabel* lb_title = [UILabel new];
    lb_title.text = @"图片编辑";
    lb_title.font = [UIFont boldSystemFontOfSize:18];
    lb_title.textAlignment = NSTextAlignmentCenter;
    lb_title.textColor = [UIColor colorWithHex:0x4d4d4d];
    [navView addSubview:lb_title];
    [lb_title mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.offset(cl_kStatusBarHeight);
        make.centerX.equalTo(navView);
        make.height.offset(44);
    }];

    //重新拍摄
    UIButton* repetBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [repetBtn setTitle:@"重新拍摄" forState:UIControlStateNormal];
    [repetBtn setTitleColor:[UIColor colorWithHex:0x4d4d4d] forState:UIControlStateNormal];
    repetBtn.frame = CGRectMake(ScreenWidth - 100, cl_kStatusBarHeight, 100, 44);
    repetBtn.titleLabel.font = [UIFont systemFontOfSize:16];
    [repetBtn addTarget:self action:@selector(repetBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    [navView addSubview:repetBtn];
    [self.view addSubview:navView];
}
#pragma mark - event response
- (void)backClick:(UIButton *)sender
{
    [self.navigationController popViewControllerAnimated:YES];
}
- (void)repetBtnClick:(UIButton *)button{
    if ([ToolsObject getAuthorizationStatus] == NO) {
        return;
    }
   NSUInteger soureceType  = UIImagePickerControllerSourceTypeCamera;
   UIImagePickerController *imagePickerController = [[UIImagePickerController alloc] init];
   imagePickerController.delegate = self;
   imagePickerController.sourceType = soureceType;
   //imagePickerController.allowsEditing = YES;
   [self presentViewController:imagePickerController animated:YES completion:nil];
}
//------------------------------cammer--------------------------------
#pragma mark - UIImagePickerControllerDelegate
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info{
    typeof(self) wSelf = self;
    dispatch_queue_t queue = dispatch_get_main_queue();
    dispatch_async(queue, ^{
        [self dismissViewControllerAnimated:YES completion:^{
            UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];
            
            wSelf.image = image;
            
            [wSelf updatePhoto];
        }];
    });
    
}
-(void)imagePickerControllerDidCancel:(UIImagePickerController *)picker{
    
    [self dismissViewControllerAnimated:YES completion:nil];
}
#pragma mark - 尺寸选择
- (IBAction)sizeSelectBtn:(UIButton *)sender {
    self.selectSizeBtn.backgroundColor = [UIColor whiteColor];
    [self.selectSizeBtn setTitleColor:K_MainColor forState:UIControlStateNormal];

    sender.backgroundColor = K_MainColor;
    [sender setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    
    if (self.selectSizeBtn.tag != sender.tag) {
        self.Sizeindex = sender.tag;
        
        [self updatePhoto];
    }
    self.selectSizeBtn = sender;
}
#pragma mark - 美白是否选择
- (IBAction)WhiteningSelect:(UIButton *)sender {
    self.WhiteningView.hidden = YES;
    self.baseColorView.hidden = NO;
    self.SaveView.hidden = NO;
    if (sender.tag == 20) {
        [self updatePhoto];
    }
}
#pragma mark - 底色选择
- (IBAction)baseColorBtn:(UIButton *)sender {
    if (self.bg_colorindex != sender.tag) {
        self.bg_colorindex = sender.tag;
        [self updatePhoto];
    }
}
#pragma mark - 底部按钮
- (IBAction)SaveBtn:(UIButton *)sender {
    if (sender.tag == 10) {
        //美化照片
        self.WhiteningView.hidden = NO;
        self.baseColorView.hidden = YES;
        self.SaveView.hidden = YES;
    }else{
        //保存到相册
        UIImageWriteToSavedPhotosAlbum(self.BaseImgView.image,self, @selector(image:didFinishSavingWithError:contextInfo:),nil);
    }
}
//保存图片完成之后的回调
- (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error
contextInfo:(void *)contextInfo
{
    // Was there an error?
    if (error != NULL)
    {
        [XYProgressHUD showMessage:@"图片保存失败"];
 //       [self alertShow:@"图片保存失败"];
    }
    else  // No errors
    {
        [XYProgressHUD showMessage:@"图片保存成功"];
 //       [self alertShow:@"图片保存成功"];
    }
}
#pragma mark - 上传图片
- (void)updatePhoto{
    NSString*version = nil;
    NSString*v = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"];
    NSArray*vArr = [v componentsSeparatedByString:@"."];
    
    for (int i = 0; i < vArr.count; i++) {
        if (version == nil) {
            version = [NSString stringWithFormat:@"%@",vArr[i]];
        }else{
            version = [version stringByAppendingFormat:@"%@",vArr[i]];
        }
    }
    NSMutableDictionary *parms = [NSMutableDictionary dictionary];
    [parms setValue:version forKey:@"ver"];
    [parms setValue:@"kksh" forKey:@"user"];
    [parms setValue:@"0.5" forKey:@"sharp"];
    [parms setValue:@"0.5" forKey:@"smooth"];
    //图片尺寸
    [parms setValue:[NSString stringWithFormat:@"%ld",(long)self.Sizeindex] forKey:@"id_photo_size"];
    //背景颜色(底色)
    if (self.bg_colorindex == 1) {
        [parms setValue:@"white" forKey:@"bg_color"];
    }else if (self.bg_colorindex == 2){
        [parms setValue:@"red" forKey:@"bg_color"];
    }else{
        [parms setValue:@"blue" forKey:@"bg_color"];
    }
    [parms setValue:[NSString stringWithFormat:@"%.2f",self.SliderView.value] forKey:@"white"];
    NSString *base64String = [ToolsObject imageUserToCompressForSizeImage:self.image newSize:CGSizeMake(1280,960)];
    [parms setValue:base64String forKey:@"base64"];
    NSString *url = [NSString stringWithFormat:@"%@face/id_photo",[NetworkConfig ipPhotoConfig]];

    [KKLoadingAnimationView show];
    typeof(self) wSelf = self;
    [NetworkRequest Post12:url Params:parms Success:^(id _Nonnull objc) {
        [KKLoadingAnimationView dismiss];
        NSLog(@"==========objc:%@",objc);
        if ([objc isKindOfClass:[NSDictionary class]]) {
            if ([objc[@"status"] intValue] == 0) {
                //            "img_height" = 4032;
                //            "img_width" = 3008;
                //            "make_cartoon_time" = "5.409633636474609";
                //            "result_64" =
                NSString *base64Str = objc[@"result_64"];
                NSData *decodeData = [[NSData alloc] initWithBase64EncodedString:base64Str options:(NSDataBase64DecodingIgnoreUnknownCharacters)];
                UIImage *decodedImage = [UIImage imageWithData: decodeData];
                wSelf.BaseImgView.image = decodedImage;
            }else{
                [XYProgressHUD showMessage:objc[@"error_info"]];
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^(void) {
                     [wSelf.navigationController popViewControllerAnimated:YES];
                });
            }
        }else{
            [XYProgressHUD showMessage:@"网络异常"];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^(void) {
                 [wSelf.navigationController popViewControllerAnimated:YES];
            });
        }
        
        
        
    } Failure:^(NSError* error) {
        [KKLoadingAnimationView dismiss];
        NSLog(@"error:%@",error);
        [XYProgressHUD showMessage:@"网络异常"];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^(void) {
             [wSelf.navigationController popViewControllerAnimated:YES];
        });
    }];
}

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