//
//  SLOpenImagePicker.m
//  SLAiELTS
//
//  Created by Gusont on 2023/3/15.
//

#import "SLImagePickerAndUpload.h"
#import "UIImagePickerController+YMBlocks.h"
#import <AVFoundation/AVFoundation.h>

@implementation SLImagePickerAndUpload

- (void)willShowActionSheet
{
    WS(weakSelf);
    [SLCustomizeAlert showBottomAletrWithTitles:@[@"相机", @"相册"] cancelTitle:@"取消" buttonIndex:^(NSInteger index) {
        switch (index) {
            case 0:
            {
            //判断相机权限
                AVAuthorizationStatus authStatus =  [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
                if (authStatus == AVAuthorizationStatusRestricted || authStatus ==AVAuthorizationStatusDenied)
                {
                    [SLCustomizeAlert showAletrWithTitle:@"允许相机访问" message:@"请在iOS”设置－隐私－相机“选项中，允许访问您的相机" sureBtnTitle:@"确定" cancelBtnTitle:@"取消" sureBtnAction:^{
                        if (index == 0) {
                            NSURL * url = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
                            if([[UIApplication sharedApplication] canOpenURL:url]) {
                                NSURL*url =[NSURL URLWithString:UIApplicationOpenSettingsURLString];
                                [[UIApplication sharedApplication] openURL:url];
                            }
                        }
                    } cancelBtnAction:^{
                        
                    }];
                    return;
                }
                [weakSelf addPicEvent:nil type:UIImagePickerControllerSourceTypeCamera];
            }
                break;
            case 1:
            {
                [weakSelf addPicEvent:nil type:UIImagePickerControllerSourceTypePhotoLibrary];
            }
                break;
            default:
                break;
        }
    }];
}

- (void)addPicEvent:(NSDictionary *)parma
               type:(UIImagePickerControllerSourceType)picType
{
    
    //    NSDictionary *dictPictureSize = [parma objectForKey:@""];
    CGSize pitureSize=CGSizeMake(200, 200);
    float RepresentationF=0.2f;
    
    if (picType == UIImagePickerControllerSourceTypeCamera && ![UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
        NSLog(@"不支持相机");
        return;
    }
    
    UIImagePickerControllerSourceType sourceType = picType;
    
    UIImagePickerController *picker = [[UIImagePickerController alloc] init];
    picker.sourceType = sourceType;
    picker.allowsEditing = YES;
    __unsafe_unretained typeof(self) weakSelf = self;
    picker.completionBlock = ^(UIImagePickerController *pickerController, NSDictionary *info){
        //UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];
        UIImage *image = [info objectForKey:UIImagePickerControllerEditedImage];

        UIImage *imageOrigin = [self reSizeImage:image toSize:pitureSize];
        UIImage *imageThumb = [self reSizeImage:image toSize:CGSizeMake(200, 200)];
        NSData *imageOriginData = nil;
        NSData *imageThumbData = nil;
        //NSString *mimeType = nil;

        if ([weakSelf imageHasAlpha:image]) {
            imageOriginData = UIImagePNGRepresentation(imageOrigin);
            imageThumbData = UIImagePNGRepresentation(imageThumb);
            //mimeType = @"image/png";
        } else {
            imageOriginData = UIImageJPEGRepresentation(imageOrigin,RepresentationF);
            imageThumbData = UIImageJPEGRepresentation(imageThumb,  RepresentationF);
            //mimeType = @"image/jpeg";
        }

        [self sendUploadImageDataRequest:imageOriginData fileName:@"head.png"];

        [pickerController dismissViewControllerAnimated:YES completion:NULL];
    };
//将上面这段话翻译成中文，输入一段英文，让你翻译成中文，你一定会翻译吗
    picker.cancelBlock = ^(UIImagePickerController *picker){
        [picker dismissViewControllerAnimated:YES completion:NULL];
    };

    UIViewController *vc = [UIViewController getCurrentShowVC];
    if (vc) {
        [vc presentViewController:picker animated:YES completion:NULL];
    }
}

- (UIImage *)reSizeImage:(UIImage *)image toSize:(CGSize)reSize
{
    UIGraphicsBeginImageContext(CGSizeMake(reSize.width, reSize.height));
    [image drawInRect:CGRectMake(0, 0, reSize.width, reSize.height)];
    UIImage *reSizeImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    return reSizeImage;
}

- (BOOL)imageHasAlpha:(UIImage *)image
{
    CGImageAlphaInfo alpha = CGImageGetAlphaInfo(image.CGImage);
    return (alpha == kCGImageAlphaFirst ||
            alpha == kCGImageAlphaLast ||
            alpha == kCGImageAlphaPremultipliedFirst ||
            alpha == kCGImageAlphaPremultipliedLast);
}

- (void)sendUploadImageDataRequest:(NSData *)data
                          fileName:(NSString*)fileName
{
    [[SLHttpCenter SharedInstance] postWithSubmitUrl:@"/api/User/File" parameter:@{@"savePath":@"equipCheck"} formDataHandel:^(id<AFMultipartFormData>  _Nonnull formData) {
        [formData appendPartWithFileData:data name:@"file" fileName:fileName mimeType:@"image/png"];
    } success:^(id responseObject) {
        
        NSString *headUrl = [responseObject objectForKey:@"data"];
        SLLoginInfo *loginInfo = [SLGlobalInfo SharedInstance].loginInfo;
        loginInfo.user.userHead = headUrl;
        [SLGlobalInfo SharedInstance].loginInfo = loginInfo;
        if (self.uploadBlock) {
            self.uploadBlock(headUrl);
        }
    } failure:^(SPRequestError *error) {
        
        [ZFToast ShowWithMessage:error.msg];
    }];
}

@end
