//
//  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:@[NSLocalizedString(@"拍照", nil), NSLocalizedString(@"选择照片", nil)] cancelTitle:NSLocalizedString(@"取消", nil) buttonIndex:^(NSInteger index) {
        switch (index) {
            case 0:
            {
                [weakSelf addPicwithCamera];
            }
                break;
            case 1:
            {
                [weakSelf addPicWithPhotoLibrary];
            }
                break;
            default:
                break;
        }
    }];
}

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

- (void)addPicWithPhotoLibrary {
    [self addPicEvent:nil type:UIImagePickerControllerSourceTypePhotoLibrary];
}

- (void)addPicEvent:(NSDictionary *)parma
               type:(UIImagePickerControllerSourceType)picType
{
    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:UIImagePickerControllerEditedImage];
        CGSize pitureSize= weakSelf.isOriginImage ? image.size : CGSizeMake(200, 200);
        UIImage *imageOrigin = weakSelf.isOriginImage ? image : [self reSizeImage:image toSize:pitureSize];
        NSData *imageOriginData = nil;
        if ([weakSelf imageHasAlpha:image]) {
            imageOriginData = UIImagePNGRepresentation(imageOrigin);
        } else {
            imageOriginData = UIImageJPEGRepresentation(imageOrigin,1.0);
        }
        NSData *imgData = [UIImage resetSizeOfImageData:[UIImage imageWithData:imageOriginData] maxSize:1024 * 3.0];
        [self sendUploadImageDataRequest:imgData 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
{
    NSString *url = @"/api/User/UploadFiles";
    NSDictionary *params = @{};
    if (self.isUploadHeadImage) {
        url = @"/api/User/File";
        params = @{@"savePath":@"equipCheck"};
    }
    [[SLHttpCenter SharedInstance] postWithSubmitUrl:url parameter:params formDataHandel:^(id<AFMultipartFormData>  _Nonnull formData) {
        [formData appendPartWithFileData:data name:@"file" fileName:fileName mimeType:@"image/png"];
    } success:^(id responseObject) {
        NSString *headUrl = [responseObject objectForKey:@"data"];
        if (self.isUploadHeadImage) {
            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
