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

#import "KKCarPictureEditVC.h"

@interface KKCarPictureEditVC ()<UINavigationControllerDelegate,UIImagePickerControllerDelegate>
@property (weak, nonatomic) IBOutlet UIImageView *BaseImgView;
@property (weak, nonatomic) IBOutlet UIView *BottomView;
@property (nonatomic, strong)UIButton *selectBtn;
@property (nonatomic, assign) NSInteger selectIndex;
@end

@implementation KKCarPictureEditVC
- (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.selectIndex = 0;
    
    self.BaseImgView.image = self.image;
    
//    [self setBottomView];
    
    [self updatePhoto];
}
- (void)setBottomView{
    NSArray *imgArr = @[@"默认风格"];
    CGFloat interval = (ScreenWidth - 60 * 4) / 5;
    for (int i = 0; i < imgArr.count; i++) {
        UIButton *button = [[UIButton alloc]initWithFrame:CGRectMake(interval + (60 + interval) * i, 60, 60, 70)];
        [button setBackgroundImage:[UIImage imageNamed:imgArr[i]] forState:UIControlStateNormal];
        button.tag = i;
        button.layer.masksToBounds = YES;
        button.layer.cornerRadius = 5;
        if (i == 0) {
            button.layer.borderColor = [UIColor redColor].CGColor;
            button.layer.borderWidth = 1;
            self.selectBtn = button;
            self.selectIndex = 0;
        }
        [button addTarget:self action:@selector(selectStyle:) forControlEvents:UIControlEventTouchUpInside];
        [self.BottomView addSubview:button];
    }
}
- (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 - 风格选择
- (void)selectStyle:(UIButton *)button{
    self.selectBtn.layer.borderColor = [UIColor clearColor].CGColor;
    self.selectBtn.layer.borderWidth = 0;
    
    button.layer.borderColor = [UIColor redColor].CGColor;
    button.layer.borderWidth = 1;
    self.selectBtn = button;
    self.selectIndex = button.tag;
    
    [self updatePhoto];
}
#pragma mark -保存相册
- (IBAction)SaveBtn:(UIButton *)sender {

   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:@"blue" forKey:@"bg_color"];
    [parms setValue:@"8" forKey:@"id_photo_size"];
    [parms setValue:version forKey:@"ver"];
    [parms setValue:@"kksh" forKey:@"user"];
    [parms setValue:@"0.5" forKey:@"sharp"];
    [parms setValue:@"0.5" forKey:@"smooth"];
    [parms setValue:@"0.5" forKey:@"white"];
    if (self.selectIndex == 1) {
        [parms setValue:@"shinkai" forKey:@"style"];
    }else if (self.selectIndex == 2){
        [parms setValue:@"hayao" forKey:@"style"];
    }else if (self.selectIndex == 3){
        [parms setValue:@"paprika" forKey:@"style"];
    }else{
        [parms setValue:@"other" forKey:@"style"];
    }
    NSString *base64String = [ToolsObject imageUserToCompressForSizeImage:self.image newSize:CGSizeMake(1280,960)];
    [parms setValue:base64String forKey:@"base64"];
    NSString *url = [NSString stringWithFormat:@"%@face/cartoon",[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
