#import "GengmeiFlutterPlugin.h"
#import <AssetsLibrary/AssetsLibrary.h>
#import <Photos/Photos.h>
#import "Image/AlbumItem.h"
#import "ResultManager.h"
#import <ImageIO/ImageIO.h>

@interface GengmeiFlutterPlugin () <UIActionSheetDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate,FlutterStreamHandler> //一定要声明这三个协议，缺一不可
//@property(nonatomic)FlutterResult  result;
@property(atomic)int needSize;
@property(atomic)int nowSize;
@property(atomic)int copySize;
@property(nonatomic) long resultKey;
@property(nonatomic)long nativeCameraKey;
@property(strong,atomic)NSMutableDictionary<NSString*,NSMutableArray<NSMutableDictionary<NSString*,NSObject*>*>*>* finalMap;
@property(nonatomic,strong) UIImagePickerController *imagePicker;
@property(atomic)Boolean quitPage;
@property(atomic)Boolean execdTask;
@property(atomic)Boolean finishScanImg;
@end

@implementation GengmeiFlutterPlugin

FlutterEventSink _eventSink;
NSMutableArray<AlbumItem *> *assetCollectionList;
UIViewController * viewController;
dispatch_queue_t queue;
NSObject<FlutterPluginRegistrar>* resign;
FlutterEventSink _eventSink;
+ (void)registerWithRegistrar:(NSObject<FlutterPluginRegistrar>*)registrar {
    GengmeiFlutterPlugin* instance = [[GengmeiFlutterPlugin alloc] init];
//    resign=registrar;
    FlutterMethodChannel* channel = [FlutterMethodChannel
                                     methodChannelWithName:@"gengmei_flutter_plugin"
                                     binaryMessenger:[registrar messenger]];
    
    [registrar addMethodCallDelegate:instance channel:channel];
    assetCollectionList = [NSMutableArray array];
    viewController =[UIApplication sharedApplication].delegate.window.rootViewController;
    queue =  dispatch_queue_create("com.gengmei_flutter_plugin", DISPATCH_QUEUE_CONCURRENT);
    FlutterEventChannel* chargingChannel = [FlutterEventChannel
                                            eventChannelWithName:@"gengmei_flutter_plugin_event"
                                            binaryMessenger:[registrar messenger]];
    [chargingChannel setStreamHandler:instance];
}


- (void)handleMethodCall:(FlutterMethodCall*)call result:(FlutterResult)result {
    self.resultKey++;
    [[ResultManager sharedSingleton] addResult:[NSNumber numberWithLong:self.resultKey] :result];
    if ([@"scan_image_picker" isEqualToString:call.method]) {
        ALAuthorizationStatus  author = [ALAssetsLibrary authorizationStatus];
        NSString *mediaType = AVMediaTypeVideo;     //读取媒体类型
        AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:mediaType];          //读取设备授权状态
        if(author == AVAuthorizationStatusRestricted || authStatus == AVAuthorizationStatusDenied) {
            NSLog(@"没给权限！！！");
        }else if(author == AVAuthorizationStatusNotDetermined){
            [PHPhotoLibrary requestAuthorization:^(PHAuthorizationStatus status) {
                if(status == PHAuthorizationStatusAuthorized) {
                    dispatch_async(dispatch_get_main_queue(), ^{
                        // 用户点击 "OK"
                        long temp=self.resultKey;
                        [self scanPhone:temp];
                    });
                } else {
                    dispatch_async(dispatch_get_main_queue(), ^{
                        // 用户点击 不允许访问
                        NSLog(@"被拒绝 TODO！！");
                    });
                }
            }];
        }else{
            NSLog(@"相机可用");
            long temp=self.resultKey;
            [self scanPhone:temp];
        }
    } else if([@"native_camera" isEqualToString:call.method]){
        self.nativeCameraKey=self.resultKey;
        NSString *mediaType = AVMediaTypeVideo;//读取媒体类型
        AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:mediaType];//读取设备授权状态
        if(authStatus == AVAuthorizationStatusRestricted || authStatus == AVAuthorizationStatusDenied){
            NSString *errorStr = @"应用相机权限受限,请在iPhone的“设置-隐私-相机”选项中，允许好享玩访问你的相机。";
            NSLog(@"相机不可用");
        }else if(authStatus == AVAuthorizationStatusNotDetermined){
            [AVCaptureDevice requestAccessForMediaType:AVMediaTypeVideo completionHandler:^(BOOL granted) {
                if(granted){
                    [self nativeCamera];
                }
            }];
        }else {
            NSLog(@"相机可用");
            [self nativeCamera];
        }
    }else if([@"quit_page" isEqualToString:call.method]){
        self.quitPage=true;
    }else if([@"SAVE_STRING_SHARED" isEqualToString:call.method]){
        long temp=self.resultKey;
        NSString *key=call.arguments[@"key"];
        NSString * value=call.arguments[@"value"];
        dispatch_async(queue, ^{
            [[NSUserDefaults standardUserDefaults] setValue:value forKey:key];
            dispatch_async(dispatch_get_main_queue(), ^{
                [[ResultManager sharedSingleton] resultSuccess:[NSNumber numberWithLong:temp] :@YES];
            });
        });
    }else if([@"SAVE_INT_SHARED" isEqualToString:call.method]){
        long temp=self.resultKey;
        NSString *key=call.arguments[@"key"];
        NSNumber* value=call.arguments[@"value"];
        dispatch_async(queue, ^{
            [[NSUserDefaults standardUserDefaults] setValue:value forKey:key];
            dispatch_async(dispatch_get_main_queue(), ^{
                [[ResultManager sharedSingleton] resultSuccess:[NSNumber numberWithLong:temp] :@YES];
            });
        });
    }else if([@"SAVE_FLOAT_SHARED" isEqualToString:call.method]){
        long temp=self.resultKey;
        NSString *key=call.arguments[@"key"];
        NSNumber* value=call.arguments[@"value"];
        dispatch_async(queue, ^{
            [[NSUserDefaults standardUserDefaults] setObject:value forKey:key];
            dispatch_async(dispatch_get_main_queue(), ^{
                [[ResultManager sharedSingleton] resultSuccess:[NSNumber numberWithLong:temp] :@YES];
            });
        });
    }
    else if([@"SAVE_BOOLEAN_SHARED" isEqualToString:call.method]){
        long temp=self.resultKey;
        NSString *key=call.arguments[@"key"];
        bool  value=call.arguments[@"value"];
        dispatch_async(queue, ^{
            [[NSUserDefaults standardUserDefaults] setBool:value forKey:key];
            dispatch_async(dispatch_get_main_queue(), ^{
                [[ResultManager sharedSingleton] resultSuccess:[NSNumber numberWithLong:temp] :@YES];
            });
        });
    }else if([@"SAVE_STRINGLIST_SHARED" isEqualToString:call.method]){
        long temp=self.resultKey;
        NSString *key=call.arguments[@"key"];
        NSArray<NSString*> * value=call.arguments[@"value"];
        dispatch_async(queue, ^{
            [[NSUserDefaults standardUserDefaults] setValue:value forKey:key];
            dispatch_async(dispatch_get_main_queue(), ^{
                [[ResultManager sharedSingleton] resultSuccess:[NSNumber numberWithLong:temp] :@YES];
            });
        });
    }else if([@"GET_STRING_SHARED" isEqualToString:call.method]){
        long temp=self.resultKey;
        NSString *key=call.arguments[@"key"];
        NSString * value=call.arguments[@"value"];
        dispatch_async(queue, ^{
            __block NSString* result=[[NSUserDefaults standardUserDefaults] objectForKey:key];
            dispatch_async(dispatch_get_main_queue(), ^{
                if(result==nil) result=value;
                [[ResultManager sharedSingleton] resultSuccess:[NSNumber numberWithLong:temp] :result];
            });
        });
    }else if([@"GET_FLOAT_SHARED" isEqualToString:call.method]){
        long temp=self.resultKey;
        NSString *key=call.arguments[@"key"];
        NSNumber* value=call.arguments[@"value"];
        dispatch_async(queue, ^{
            __block NSNumber* result=[[NSUserDefaults standardUserDefaults] objectForKey:key];
            dispatch_async(dispatch_get_main_queue(), ^{
                if(result==nil) result=value;
                [[ResultManager sharedSingleton] resultSuccess:[NSNumber numberWithLong:temp] :result];
            });
        });
    }else if([@"GET_INT_SHARED" isEqualToString:call.method]){
        long temp=self.resultKey;
        NSString *key=call.arguments[@"key"];
        NSNumber* value=call.arguments[@"value"];
        dispatch_async(queue, ^{
            __block NSNumber* result=[[NSUserDefaults standardUserDefaults] objectForKey:key];
            dispatch_async(dispatch_get_main_queue(), ^{
                if(result==nil) result=value;
                [[ResultManager sharedSingleton] resultSuccess:[NSNumber numberWithLong:temp] :result];
            });
        });
    }else if([@"GET_BOOLEAN_SHARED" isEqualToString:call.method]){
        long temp=self.resultKey;
        NSString *key=call.arguments[@"key"];
        NSNumber * value=call.arguments[@"value"];
        dispatch_async(queue, ^{
            __block NSNumber* result=[[NSUserDefaults standardUserDefaults] objectForKey:key];
            dispatch_async(dispatch_get_main_queue(), ^{
                if(result==nil) result=value;
                [[ResultManager sharedSingleton] resultSuccess:[NSNumber numberWithLong:temp] :result];
            });
        });
    }else if([@"GET_STRINGLIST_SHARED" isEqualToString:call.method]){
        long temp=self.resultKey;
        NSString *key=call.arguments[@"key"];
        NSArray<NSString*> * value=call.arguments[@"value"];
        dispatch_async(queue, ^{
            __block NSArray<NSString*>* result=[[NSUserDefaults standardUserDefaults] objectForKey:key];
            dispatch_async(dispatch_get_main_queue(), ^{
                if(result==nil) result=value;
                [[ResultManager sharedSingleton] resultSuccess:[NSNumber numberWithLong:temp] :result];
            });
        });
    }
    else{
        result(FlutterMethodNotImplemented);
    }
}



-(void)nativeCamera{
    self.imagePicker = [[UIImagePickerController alloc] init];
    // 设置代理
    self.imagePicker.delegate = self;
    // 是否显示裁剪框编辑（默认为NO），等于YES的时候，照片拍摄完成可以进行裁剪
    self.imagePicker.allowsEditing = NO;
    // 设置照片来源为相机
    self.imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera;
    // 设置进入相机时使用前置或后置摄像头
    self.imagePicker.cameraDevice = UIImagePickerControllerCameraDeviceRear;
    // 展示选取照片控制器
    [viewController presentViewController:self.imagePicker animated:YES completion:nil];
}

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
    NSString *cacheDirectory = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) firstObject];
    UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];
    NSData *data;

    data= UIImagePNGRepresentation(image);
    //    if (UIImagePNGRepresentation(image) == nil){
    //        data = UIImageJPEGRepresentation(image, 1);
    //    }   else {
    //        data = UIImagePNGRepresentation(image);
    //    }
    NSString *guid = [[NSProcessInfo processInfo] globallyUniqueString];
    NSString *tmpFile = [NSString stringWithFormat:@"image_picker_%@", guid];
    NSString* tmpPath= [cacheDirectory stringByAppendingPathComponent:tmpFile];
    if ([[NSFileManager defaultManager] createFileAtPath:tmpPath contents:data attributes:nil]) {
        dispatch_async(dispatch_get_main_queue(), ^{
            [[ResultManager sharedSingleton] resultSuccess:[NSNumber numberWithLong:self.nativeCameraKey] :tmpPath];
        });
    } else {
        dispatch_async(dispatch_get_main_queue(), ^{
            [[ResultManager sharedSingleton] resultSuccess:[NSNumber numberWithLong:self.nativeCameraKey] :@""];
        });
    }
    [picker dismissViewControllerAnimated:YES completion:nil];
    /* 此处参数 info 是一个字典，下面是字典中的键值 （从相机获取的图片和相册获取的图片时，两者的info值不尽相同）
     * UIImagePickerControllerMediaType; // 媒体类型
     * UIImagePickerControllerOriginalImage; // 原始图片
     * UIImagePickerControllerEditedImage; // 裁剪后图片
     * UIImagePickerControllerCropRect; // 图片裁剪区域（CGRect）
     * UIImagePickerControllerMediaURL; // 媒体的URL
     * UIImagePickerControllerReferenceURL // 原件的URL
     * UIImagePickerControllerMediaMetadata // 当数据来源是相机时，此值才有效
     */
    // 从info中将图片取出，并加载到imageView当中
    //    UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];
    //    self.imageView.image = image;
    //    // 创建保存图像时需要传入的选择器对象（回调方法格式固定）
    //    SEL selectorToCall = @selector(image:didFinishSavingWithError:contextInfo:);
    //    // 将图像保存到相册（第三个参数需要传入上面格式的选择器对象）
    //    UIImageWriteToSavedPhotosAlbum(image, self, selectorToCall, NULL);
}

// 取消选取调用的方法
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
    [viewController dismissViewControllerAnimated:YES completion:nil];
    [[ResultManager sharedSingleton] resultSuccess:[NSNumber numberWithLong:self.nativeCameraKey] :@""];
}

-(void)scanPhone:(long)resultId{
    self.quitPage=false;
    if (self.finalMap==nil) {
        self.finalMap=[NSMutableDictionary dictionary];
    }
    if ([self.finalMap count]>0&&self.finishScanImg) {
        [self resultImgs:resultId];
        return;
    }
    self.nowSize=0;
    self.needSize=0;
    [self.finalMap removeAllObjects];
    [assetCollectionList removeAllObjects];
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
        [self scanPhoneImage];
        [self copyImg:resultId];
    });
}

-(void)scanPhoneImage{
    PHFetchResult<PHAssetCollection *> *favoritesCollection = [PHAssetCollection fetchAssetCollectionsWithType:PHAssetCollectionTypeSmartAlbum subtype:PHAssetCollectionSubtypeSmartAlbumFavorites options:NO];
    // 获得相机胶卷
    PHFetchResult<PHAssetCollection *> *assetCollections = [PHAssetCollection fetchAssetCollectionsWithType:PHAssetCollectionTypeAlbum subtype:PHAssetCollectionSubtypeSmartAlbumUserLibrary options:NO];
    // 获得全部相片
    PHFetchResult<PHAssetCollection *> *cameraRolls = [PHAssetCollection fetchAssetCollectionsWithType:PHAssetCollectionTypeSmartAlbum subtype:PHAssetCollectionSubtypeSmartAlbumUserLibrary options:NO];
    
    for (PHAssetCollection *collection in cameraRolls) {
        AlbumItem *model = [[AlbumItem alloc] init];
        model.collection = collection;
        if (model.collectionNumber !=0) {
            [assetCollectionList addObject:model];
        }
    }
    
    for (PHAssetCollection *collection in favoritesCollection) {
        AlbumItem *model = [[AlbumItem alloc] init];
        model.collection = collection;
        if (model.collectionNumber !=0) {
            [assetCollectionList addObject:model];
        }
    }
    
    for (PHAssetCollection *collection in assetCollections) {
        AlbumItem *model = [[AlbumItem alloc] init];
        model.collection = collection;
        
        if (model.collectionNumber!=0) {
            [assetCollectionList addObject:model];
        }
    }
    for (AlbumItem* item in assetCollectionList) {
        self.needSize+=[item collectionNumber];
    }
}

-(void)resultImgs:(long)resultId{
    if(self.quitPage){
        return;
    }
    dispatch_async(dispatch_get_main_queue(), ^{
        self.finishScanImg=true;
        [[ResultManager sharedSingleton] resultSuccess:[NSNumber numberWithLong:resultId] :self.finalMap];
        if(self.execdTask){
            return ;
        }
        self.execdTask=true;
        [NSThread detachNewThreadWithBlock:^{
            NSLog(@"block run...");
            [self execRealImg];
        }];
//        [self performSelectorInBackground:@selector(run) withObject:nil];
//        dispatch_queue_t queue1 = dispatch_queue_create("com.onealon.gcdTest1", DISPATCH_QUEUE_CONCURRENT);
//        dispatch_sync(queue1, ^{
//
//        });
    });

}


-(void)upImgs{
    dispatch_async(dispatch_get_main_queue(), ^{
        if(_eventSink!=nil&&!self.quitPage){
            _eventSink(self.finalMap);
        }
    });
}

-(void) copyImg:(long)resultId{
    NSString *cacheDirectory = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) firstObject];
    NSFileManager *fileManager = [NSFileManager defaultManager];
    for (int j=0; j<assetCollectionList.count; j++) {
        AlbumItem * item=assetCollectionList[j];
        PHFetchResult<PHAsset *> * assetResult =[item assets];
        for (int i=0; i<[assetResult count]; i++) {
            __block NSString* docName=[item collectionTitle];
            PHAsset * assets=[assetResult objectAtIndex:i];
            __block NSString * imgName=[assets valueForKey:@"filename"];
            if (imgName==nil) {
                NSLog(@"NEWWWW!!!!! image name is Null!!!  ");
                NSString *timeSp = [NSString stringWithFormat:@"%ld", (long)([[NSDate date] timeIntervalSince1970]*100000)];
                imgName=[NSString stringWithFormat:@"IMG_%@",timeSp];
            }
            __block NSString *tmpPath=[cacheDirectory stringByAppendingPathComponent:imgName];
            if ([fileManager fileExistsAtPath:tmpPath]==YES){
                self.nowSize++;
                NSMutableDictionary* queryItemDict = [NSMutableDictionary dictionary];
                [queryItemDict setObject:tmpPath forKey:@"path"];
                NSMutableArray * arr=self.finalMap[docName];
                if (arr==nil) {
                    self.finalMap[docName]=[NSMutableArray array];
                    [self.finalMap[docName] addObject:queryItemDict];
                }else{
                    [self.finalMap[docName] addObject:queryItemDict];
                }
                NSLog(@"SCARE SIZEEE  %d %d ",self.nowSize,self.needSize);
                if (self.nowSize==self.needSize) {
                    [self resultImgs:resultId];
                }
            }else{
                PHImageRequestOptions *imageRequestOption = [[PHImageRequestOptions alloc] init];
                imageRequestOption.synchronous =NO;
                int picWidth=[assets pixelWidth];
                int picHeight=[assets pixelHeight];
                float tempScareSize=1;
                if(picWidth>picHeight){
                    if (picWidth>320.0) {
                        tempScareSize=320.0/picWidth;
                    }
                }else{
                    if (picHeight>320.0) {
                        tempScareSize=320.0/picHeight;
                    }
                }
                CGSize temp=CGSizeMake(picWidth*tempScareSize, picHeight*tempScareSize);
                imageRequestOption.networkAccessAllowed = YES;
                imageRequestOption.deliveryMode=PHImageRequestOptionsDeliveryModeHighQualityFormat;
                //PHImageRequestOptionsDeliveryModeHighQualityFormat。//PHImageRequestOptionsDeliveryModeFastFormat
//                imageRequestOption.deliveryMode=PHImageRequestOptionsDeliveryModeFastFormat;
                imageRequestOption.resizeMode=PHImageRequestOptionsResizeModeFast;
                imageRequestOption.version=PHImageRequestOptionsVersionUnadjusted;
                //PHImageManagerMaximumSize
                [[PHImageManager defaultManager] requestImageForAsset:assets targetSize:temp contentMode:PHImageContentModeDefault options:imageRequestOption resultHandler:^(UIImage * _Nullable result, NSDictionary * _Nullable info) {
                    @autoreleasepool{
                        NSData *data = UIImageJPEGRepresentation(result, 0.7) ;
                        [data writeToFile:tmpPath atomically:YES];
                        data=nil;
                        result=nil;
                    }
//                    [UIImageJPEGRepresentation(result,1) writeToFile:tmpPath atomically:YES];
//                    [UIImageJPEGRepresentation([self image:result byScalingToSize:temp],0.8) writeToFile:realPath atomically:YES ];
                    NSMutableDictionary* queryItemDict = [NSMutableDictionary dictionary];
                    [queryItemDict setObject:tmpPath forKey:@"path"];
                    [queryItemDict setObject:imgName forKey:@"name"];
                    NSMutableArray * arr=self.finalMap[docName];
                    self.nowSize++;
                    if (arr==nil) {
                        self.finalMap[docName]=[NSMutableArray array];
                        [self.finalMap[docName] addObject:queryItemDict];
                    }else{
                        [self.finalMap[docName] addObject:queryItemDict];
                    }
                    NSLog(@"SCARE SIZEEE  %d %d ",self.nowSize,self.needSize);
                    result=nil;
                    if (self.nowSize==self.needSize) {
                        [self resultImgs:resultId];
                    }
                }];
            }
        }
    }
}

-(void)execRealImg{
    self.nowSize=0;
    self.copySize=0;
    NSString *cacheDirectory = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) firstObject];
    NSFileManager *fileManager = [NSFileManager defaultManager];
    for (int j=0; j<assetCollectionList.count; j++) {
        AlbumItem * item=assetCollectionList[j];
        PHFetchResult<PHAsset *> * assetResult =[item assets];
        NSLog(@"09090909090  %d  %d",[assetResult count],self.needSize);
        for (int i=0; i<[assetResult count]; i++) {
            __block NSString* docName=[item collectionTitle];
            PHAsset * assets=[assetResult objectAtIndex:i];
            __block NSString * imgName=[assets valueForKey:@"filename"];
            NSString * imgRealName=[NSString stringWithFormat:@"%@_REAL",imgName];
            if (imgName==nil) {
                NSLog(@"NEWWWW!!!!! image name is Null!!!  ");
                NSString *timeSp = [NSString stringWithFormat:@"%ld", (long)([[NSDate date] timeIntervalSince1970]*100000)];
                imgName=[NSString stringWithFormat:@"IMG_%@",timeSp];
                imgRealName=[NSString stringWithFormat:@"REAL_PATH_IMG_%@",timeSp];
            }
            __block NSString *realPath=[cacheDirectory stringByAppendingPathComponent:imgRealName];
            __block NSString *tmpPath=[cacheDirectory stringByAppendingPathComponent:imgName];
            if ([fileManager fileExistsAtPath:realPath]==YES){
                self.nowSize++;
                NSLog(@"!!!REAL IS EXIE!!  %@",realPath);
                NSMutableArray<NSMutableDictionary<NSString*,NSObject*>*>* array=self.finalMap[docName];
                for (int x=0; x<[array count]; x++) {
                    NSMutableDictionary<NSString*,NSObject*>* map=[array objectAtIndex:x];
                    NSString* index=[map objectForKey:@"path"];
                    if ([index isEqualToString:tmpPath]) {
                        [map setObject:realPath forKey:@"realPath"];
                        break;
                    }
                }
                NSLog(@"SIZEEE  %d %d ",self.nowSize,self.needSize);
                if (self.nowSize==self.needSize) {
                    [self upImgs];
                    self.execdTask=true;
                }
            }else{
                NSLog(@"file NOT EXIT !!  ");
                PHImageRequestOptions *imageRequestOption = [[PHImageRequestOptions alloc] init];
                imageRequestOption.synchronous =YES;
                int picWidth=[assets pixelWidth];
                int picHeight=[assets pixelHeight];
                float tempScareSize=1;
                float limit=1560.0;
                if(picWidth>picHeight){
                    if (picWidth>limit) {
                        tempScareSize=limit/picWidth;
                    }
                }else{
                    if (picHeight>limit) {
                        tempScareSize=limit/picHeight;
                    }
                }
                NSLog(@"SCARE SZIE %d %d %f  %f %f",picWidth,picHeight,tempScareSize,picWidth*tempScareSize,picHeight*tempScareSize);
                CGSize temp=CGSizeMake(picWidth*tempScareSize, picHeight*tempScareSize);
                imageRequestOption.networkAccessAllowed = YES;
                imageRequestOption.deliveryMode=PHImageRequestOptionsDeliveryModeHighQualityFormat;
                //                imageRequestOption.deliveryMode=PHImageRequestOptionsDeliveryModeFastFormat;
                imageRequestOption.resizeMode=PHImageRequestOptionsResizeModeFast;
                imageRequestOption.version=PHImageRequestOptionsVersionUnadjusted;
                [[PHImageManager defaultManager] requestImageDataForAsset:assets options:imageRequestOption resultHandler:^(NSData * _Nullable imageData, NSString * _Nullable dataUTI, UIImageOrientation orientation, NSDictionary * _Nullable info) {
//                    UIImage *image = [UIImage imageWithData:imageData];
                    [imageData writeToFile:realPath atomically:YES];
                    //获取照片 image
                    self.nowSize++;
                    self.copySize++;
                    NSMutableArray<NSMutableDictionary<NSString*,NSObject*>*>* array=self.finalMap[docName];
                    for (int x=0; x<[array count]; x++) {
                        NSMutableDictionary<NSString*,NSObject*>* map=[array objectAtIndex:x];
                        NSString* index=[map objectForKey:@"path"];
                        if ([index isEqualToString:tmpPath]) {
                            [map setObject:realPath forKey:@"realPath"];
                            break;
                        }
                    }
                    NSLog(@"SIZEEE  %d %d  %d",self.nowSize,self.needSize,self.copySize);
//                    result=nil;
                    if (self.nowSize==self.needSize) {
                        [self upImgs];
                        self.execdTask=true;
                    }else if(self.copySize%35==0||self.copySize==10){
                        NSLog(@"UPPP!!");
                        [self upImgs];
                    }
                }];
            }
        }
    }
}

-(void)writeImage:(UIImage *)image dest:(NSString*)path{
    @autoreleasepool {
        CFURLRef url=(__bridge CFURLRef)[NSURL fileURLWithPath:path];
        CGImageDestinationRef des=CGImageDestinationCreateWithURL(url, CFSTR("public.png"), 1, NULL);
        if(!des){
            NSLog(@"wrong");
            return;
        }
        CGImageDestinationAddImage(des, image.CGImage, nil);
        if(!CGImageDestinationFinalize(des)){
            NSLog(@"wrong222");
        }
        CFRelease(des);
    }
}



- (UIImage *)image:(UIImage*)image byScalingToSize:(CGSize)targetSize {
    UIImage *sourceImage = image;
    UIImage *newImage = nil;
    
    UIGraphicsBeginImageContext(targetSize);
    
    CGRect thumbnailRect = CGRectZero;
    thumbnailRect.origin = CGPointZero;
    thumbnailRect.size.width  = targetSize.width;
    thumbnailRect.size.height = targetSize.height;
    
    [sourceImage drawInRect:thumbnailRect];
    
    newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    return newImage ;
}

-(NSData *)compressWithLengthLimit:(UIImage*) img max:(NSUInteger)maxLength{
    // Compress by quality
    CGFloat compression = 1;
    NSData *data = UIImageJPEGRepresentation(img, compression);
    //NSLog(@"Before compressing quality, image size = %ld KB",data.length/1024);
    if (data.length < maxLength) return data;
    
    CGFloat max = 1;
    CGFloat min = 0;
    for (int i = 0; i < 6; ++i) {
        compression = (max + min) / 2;
        data = UIImageJPEGRepresentation(img, compression);
        //NSLog(@"Compression = %.1f", compression);
        //NSLog(@"In compressing quality loop, image size = %ld KB", data.length / 1024);
        if (data.length < maxLength * 0.9) {
            min = compression;
        } else if (data.length > maxLength) {
            max = compression;
        } else {
            break;
        }
    }
    //NSLog(@"After compressing quality, image size = %ld KB", data.length / 1024);
    if (data.length < maxLength) return data;
    UIImage *resultImage = [UIImage imageWithData:data];
    // Compress by size
    NSUInteger lastDataLength = 0;
    while (data.length > maxLength && data.length != lastDataLength) {
        lastDataLength = data.length;
        CGFloat ratio = (CGFloat)maxLength / data.length;
        //NSLog(@"Ratio = %.1f", ratio);
        CGSize size = CGSizeMake((NSUInteger)(resultImage.size.width * sqrtf(ratio)),
                                 (NSUInteger)(resultImage.size.height * sqrtf(ratio))); // Use NSUInteger to prevent white blank
        UIGraphicsBeginImageContext(size);
        [resultImage drawInRect:CGRectMake(0, 0, size.width, size.height)];
        resultImage = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
        data = UIImageJPEGRepresentation(resultImage, compression);
        //NSLog(@"In compressing size loop, image size = %ld KB", data.length / 1024);
    }
    //NSLog(@"After compressing size loop, image size = %ld KB", data.length / 1024);
    return data;
}

- (NSMutableDictionary*)useToFetchCollection {
    NSMutableDictionary* queryItemDict = [NSMutableDictionary dictionary];
    PHFetchResult<PHAssetCollection *> * collectionResult = [PHAssetCollection fetchAssetCollectionsWithType:PHAssetCollectionTypeMoment subtype:PHAssetCollectionSubtypeSmartAlbumFavorites options:nil];
    
    if (collectionResult.count == 0) {
        return queryItemDict;
    }
    PHFetchOptions *option = [[PHFetchOptions alloc] init];
    //ascending 为YES时，按照照片的创建时间升序排列;为NO时，则降序排列
    option.sortDescriptors = @[[NSSortDescriptor sortDescriptorWithKey:@"creationDate" ascending:YES]];
    PHAssetCollection* item=[collectionResult objectAtIndex:1];
    
    
    [collectionResult enumerateObjectsWithOptions:option usingBlock:^(PHAssetCollection * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        NSLog(@"%@--%@--%@", obj.localIdentifier, obj.localizedTitle,obj);
        PHFetchResult<PHAsset *> * assetResult = [PHAsset fetchAssetsInAssetCollection:obj options:NO];
        NSLog(@"INITTT  %d",collectionResult.count);
        //HashMap<String, ArrayList<HashMap<String, Any>>>
        for (int i=0; i<[assetResult count]; i++) {
            PHAsset * assets=[assetResult objectAtIndex:i];
            NSArray* tempArray=[NSArray array];
            if (assets.mediaType != PHAssetMediaTypeVideo){
                
            }
            
            [[PHImageManager defaultManager] requestImageForAsset:assets targetSize:PHImageManagerMaximumSize contentMode:PHImageContentModeDefault options:nil resultHandler:^(UIImage * _Nullable result, NSDictionary * _Nullable info) {
                //                NSLog(@"INITTT___))))00000  %d   %d  %@",i,[assetResult count],info);
                NSURL * url = [info objectForKey:@"PHImageFileURLKey"];
                NSLog(@"INITTT___))))00000 %@",url);
                NSData *data = [NSData dataWithContentsOfURL:url];
                UIImage* image = [UIImage imageWithData:data];
                //                CGSize size;
                //                if(image)
                //                {
                //                    size = image.size;
                //                }
                //                NSLog(@"INFO  %d",size);
                NSString *guid = [[NSProcessInfo processInfo] globallyUniqueString];
                NSString *tmpFile = [NSString stringWithFormat:@"image_picker_%@.JPG", guid];
                //            NSString *tmpDirectory = NSHomeDirectory();
                NSString *tmpDirectory = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) firstObject];
                //            NSString *tmpDirectory = NSTemporaryDirectory();
                NSString *tmpPath = [tmpDirectory stringByAppendingPathComponent:tmpFile];
                if ([[NSFileManager defaultManager] createFileAtPath:tmpPath contents:data attributes:nil]) {
                    NSLog(@"result  %@",tmpPath);
                } else {
                    NSLog(@"ERRORRRR  ");
                }
                //            NSLog(@"YEEEEEEE %@",url);
            }];
        }
    }];
    return queryItemDict;
}

- (void) findAllFiles{
    NSFileManager *fileManager = [NSFileManager defaultManager];
    //在这里获取应用程序Documents文件夹里的文件及文件夹列表
    //    NSArray *documentPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    //            NSString *documentDir = [documentPaths objectAtIndex:0];
    //    NSString *tmpDirectory = NSTemporaryDirectory();
    //     NSString *tmpDirectory = NSHomeDirectory();
    
    NSString *tmpDirectory = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) firstObject];
    NSError *error = nil;
     NSArray *fileList = [[NSArray alloc] init];
    //fileList便是包含有该文件夹下所有文件的文件名及文件夹名的数组
    fileList = [fileManager contentsOfDirectoryAtPath:tmpDirectory error:&error];
    NSMutableArray *dirArray = [[NSMutableArray alloc] init];
    //在上面那段程序中获得的fileList中列出文件夹名
    for (NSString *file in fileList) {
        NSString *path = [tmpDirectory stringByAppendingPathComponent:file];
        NSLog(@"patH!!!  %@",path);
    }
}

- (FlutterError* _Nullable)onListenWithArguments:(id _Nullable)arguments
                                       eventSink:(FlutterEventSink)events{
    NSLog(@"QWEQWEQEW");
    _eventSink = events;
    return nil;
}

- (FlutterError* _Nullable)onCancelWithArguments:(id _Nullable)arguments{
    _eventSink = nil;
    NSLog(@"QWEQWEQEW");
    return nil;
}
@end
