//
//  CDVEditImageTool.m
//  智慧工地UAT
//
//  Created by AllenLiu on 2019/4/25.
//

#import "CDVEditImageTool.h"
#import "LFPhotoEditingController.h"
#import <AssetsLibrary/AssetsLibrary.h>
#import "TCLocationTool.h"
#import <objc/message.h>

@interface CDVEditImageTool()<LFPhotoEditingControllerDelegate>

@property (nonatomic, strong) CDVInvokedUrlCommand *editCommand;

@property (nonatomic, copy) NSString *locationStr;

@property (nonatomic, assign) BOOL isReturnUrl;

@property (nonatomic, copy) NSString *waterText;


@end

@implementation CDVEditImageTool

- (void)showImageEditTool:(CDVInvokedUrlCommand *)command{
    
    self.editCommand = command;
    self.isReturnUrl = [[command argumentAtIndex:0] boolValue];
    UIImage *image = nil;
    if (!self.isReturnUrl) {//base64
        NSString *base64 = [command argumentAtIndex:1];
        NSData *data = [[NSData alloc] initWithBase64EncodedString:base64 options:NSDataBase64DecodingIgnoreUnknownCharacters];
        image = [UIImage imageWithData:data];
    }else{
        NSString *imgUrlStr = [command argumentAtIndex:1];
        NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:imgUrlStr]];
        image = [UIImage imageWithData:data];
    }
    
    if (command.arguments.count > 2) {//如果有水印附加参数
        self.waterText = [command argumentAtIndex:2];
    }
    
    LFPhotoEditingController *photoEditVC = [[LFPhotoEditingController alloc] init];
    photoEditVC.delegate = self;
    photoEditVC.editImage = image;
    [photoEditVC setModalPresentationStyle: UIModalPresentationFullScreen];
    [[UIApplication sharedApplication].keyWindow.rootViewController presentViewController:photoEditVC animated:YES completion:nil];
    
    
    [[TCLocationTool shareLocationTool] getLocationSuccess:^(TCLocation *location) {
        self.locationStr = [NSString stringWithFormat:@"%@ %@",location.province,location.cityName];
    } failure:^(NSError *error) {
        
    }];
    
}

#pragma mark - LFPhotoEditingControllerDelegate

- (void)lf_PhotoEditingController:(LFPhotoEditingController *)photoEditingVC didFinishPhotoEdit:(LFPhotoEdit *)photoEdit{
    
    [photoEditingVC dismissViewControllerAnimated:YES completion:nil];
    
    UIImage *resImg = nil;
    if (photoEdit) {
        resImg = photoEdit.editPreviewImage;
    }else{
        resImg = photoEditingVC.editImage;
    }
    //加水印
    UIImage *newImg = [self drawWaterText:resImg];
    
    //将图片写入相册
    ALAssetsLibrary* library = [ALAssetsLibrary new];
    [library writeImageToSavedPhotosAlbum:newImg.CGImage orientation:(ALAssetOrientation)(newImg.imageOrientation) completionBlock:^(NSURL *assetURL, NSError *error) {
        CDVPluginResult* res = nil;
        if (self.isReturnUrl) {//如果是要返回URI
            if (error) {
                res = [CDVPluginResult resultWithStatus:CDVCommandStatus_IO_EXCEPTION messageAsString:[error localizedDescription]];
            } else {
                NSString *nativeUri = [[self urlTransformer:assetURL] absoluteString];
                res = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:nativeUri];
                [self.commandDelegate sendPluginResult:res callbackId:self.editCommand.callbackId];
            }
        }
    }];
    
    if (!self.isReturnUrl) {
        NSData *data = UIImageJPEGRepresentation(resImg, 1);
        NSString *base64Str = [data base64EncodedStringWithOptions:0];
        CDVPluginResult *res = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:base64Str];
        //回调
        [self.commandDelegate sendPluginResult:res callbackId:self.editCommand.callbackId];
    }
}

//加水印
- (UIImage *)drawWaterText:(UIImage *)image{
    
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    formatter.dateFormat = @"YYYY-MM-dd HH:mm";
    NSString *timeStr = [formatter stringFromDate:[NSDate date]];
    NSString *resText = [NSString stringWithFormat:@"%@ %@",timeStr,self.locationStr];
    
    if (self.waterText) {
        resText = [NSString stringWithFormat:@"%@ %@",self.waterText,resText];
    }
    
    //1、开启图片上下文
    UIGraphicsBeginImageContextWithOptions(image.size, NO, 1);
    //2、将图片绘制到上下文
    [image drawInRect:CGRectMake(0, 0, image.size.width, image.size.height)];
    
    NSLog(@"orgImage.size:%@",NSStringFromCGSize(image.size));
    
    //图片的真实尺寸跟屏幕是显示的尺寸是不一样的
    CGFloat scale = image.size.width / [UIScreen mainScreen].bounds.size.width;
    NSDictionary *attributes = @{
                                 NSFontAttributeName:[UIFont systemFontOfSize:15 * scale],
                                 NSForegroundColorAttributeName:[UIColor redColor],
                                 };
    [resText drawInRect:CGRectMake(image.size.width - 240 * scale, image.size.height - 20 * scale, 240 * scale, 20 * scale) withAttributes:attributes];
    
    UIImage *resImg = UIGraphicsGetImageFromCurrentImageContext();
    
    //关闭图形上下文
    UIGraphicsEndImageContext();
    
    return resImg;
}

- (void)lf_PhotoEditingController:(LFPhotoEditingController *)photoEditingVC didCancelPhotoEdit:(LFPhotoEdit *)photoEdit{
    [photoEditingVC dismissViewControllerAnimated:YES completion:nil];
}


- (NSURL*) urlTransformer:(NSURL*)url
{
    NSURL* urlToTransform = url;
    
    // for backwards compatibility - we check if this property is there
    SEL sel = NSSelectorFromString(@"urlTransformer");
    if ([self.commandDelegate respondsToSelector:sel]) {
        // grab the block from the commandDelegate
        NSURL* (^urlTransformer)(NSURL*) = ((id(*)(id, SEL))objc_msgSend)(self.commandDelegate, sel);
        // if block is not null, we call it
        if (urlTransformer) {
            urlToTransform = urlTransformer(url);
        }
    }
    
    return urlToTransform;
}


@end


