//
//  ImageBrowserViewController.m
//  TaiZhouTobacco_7s
//
//  Created by JianjiYuan on 14-9-11.
//  Copyright (c) 2014年 JianjiYuan. All rights reserved.
//

#import "ImageBrowserViewController.h"
#import "ImageBrowserCell.h"
#import "UIImage+Customized.h"
#import <UIImageView+WebCache.h>
#import <MWPhotoBrowser.h>
#import <AssetsLibrary/AssetsLibrary.h>
#import "BaseImagePickerController.h"

@interface ImageBrowserViewController () < UINavigationControllerDelegate, UIImagePickerControllerDelegate,
UICollectionViewDataSource, UICollectionViewDelegate, MWPhotoBrowserDelegate, ImageBrowserCellDelegate >
{
    BOOL isAddImageAction;
}

@property (nonatomic, strong) NSMutableArray *arrContents;
@property (nonatomic, strong) NSMutableArray *arrDeletedImages;

@property (nonatomic, strong) NSMutableArray *photos;
@property (nonatomic, strong) NSMutableArray *thumbs;
@property (nonatomic, strong) NSMutableArray *selections;
@property (nonatomic, strong) ALAssetsLibrary *assetLibrary;
@property (nonatomic, strong) NSMutableArray *assets;


@end

@implementation ImageBrowserViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        self.showAddPicsButton = YES;
        self.edgeInset = UIEdgeInsetsMake(5, 20, 5, 20);
       // self.itemSize = CGSizeMake(120, 120);
        self.itemSize=CGSizeMake(130, 130);
        
        isAddImageAction = NO;
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.title = @"选择图片";
    
    UIButton *btnBack = [UIButton buttonWithType:UIButtonTypeCustom];
    [btnBack setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [btnBack setTitle:@"返 回" forState:UIControlStateNormal];
    btnBack.titleLabel.font = [UIFont systemFontOfSize:14];
    [btnBack sizeToFit];
    [btnBack addTarget:self action:@selector(btnBackClick:) forControlEvents:UIControlEventTouchUpInside];
    [self.navigationController navbarLeftItemCustomized:@[btnBack] onwer:self.navigationItem];
    
    [self.collectionView autoPinEdgesToSuperviewEdgesWithInsets:UIEdgeInsetsMake(0, 0, 0, 0)];
    
    [self reloadImageDatas];
    
    if (self.photoSource == ImageBrowserPhotoSourceAsset)
    {
        [self loadAssets];
    }
    
}

- (void)reloadImageDatas
{
    self.arrContents = [NSMutableArray array];
    [self.arrContents addObjectsFromArray:_selectedImages];
    
    if (self.showAddPicsButton) {
        ImageBrowserObj *obj = [[ImageBrowserObj alloc] init];
        obj.imageName = @"Upload/btn_takepic.png";
        obj.isAddPicsButton = YES;
        obj.isDeletable = NO;
        
        obj.itemType = ImageItemTypeAddButton;
        obj.sourceType = ImageSourceTypeBundle;
        [self.arrContents addObject:obj];
    }
    [self.collectionView reloadData];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return 1;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView
     numberOfItemsInSection:(NSInteger)section
{
    return _arrContents.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView
                 cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    ImageBrowserCell *myCell = [collectionView
                                    dequeueReusableCellWithReuseIdentifier:@"ImageBrowserCell"
                                      forIndexPath:indexPath];

    ImageBrowserObj *obj = _arrContents[indexPath.row];
    UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapProfileImage:)];
    singleTap.numberOfTapsRequired = 1;
    myCell.imageVPhoto.userInteractionEnabled = YES;
    [myCell.imageVPhoto addGestureRecognizer:singleTap];
    //myCell.canBeDelete = obj.isDeletable;
    myCell.delegate = self;
    
    
    if([obj.imageName isEqualToString:@"Upload/btn_takepic.png"])
    {
        myCell.backgroundColor = [UIColor whiteColor];
        obj.isDeletable=NO;
    }
    else
    {
        if (obj.isBGGray == YES) {
            myCell.backgroundColor = RGBColor(216, 216, 216, 1);
        }
        else
        {
            myCell.backgroundColor = [UIColor whiteColor];
        }
        obj.isDeletable=YES;
    }
   //if ((self.editing && obj.isDeletable) || (obj.isDeletable && obj.isShaking))
      if ((self.editing && obj.isDeletable) )
    {
        [myCell beginShake];
        obj.isShaking = YES;
        
    }
    else
    {
        [myCell stopShake];
        obj.isShaking = NO;
        
    }
    
    myCell.tag = indexPath.row;
    myCell.imageVPhoto.tag = [indexPath row];
    myCell.btnDelete.tag = indexPath.row;
    myCell.btnDelete.hidden = !(obj.isDeletable && obj.isShaking);

    
    
    
    [myCell.btnDelete addTarget:self action:@selector(deletePhoto:)
               forControlEvents:UIControlEventTouchUpInside];
    
    
    if (obj.imageSavedData) {
        myCell.imageVPhoto.image = [UIImage imageWithData:obj.imageSavedData scale:0.3];
     
    }else {
        switch (obj.sourceType) {
            case ImageSourceTypeBundle:
                [myCell.imageVPhoto setImage:[UIImage imageNamed:obj.imageName]];
                break;
            case ImageSourceTypeFilePath:
                myCell.imageVPhoto.image = [UIImage imageWithContentsOfFile:obj.imagePath];
                break;
            case ImageSourceTypeWebURL:
            {
                [myCell.imageVPhoto sd_setImageWithURL:[NSURL URLWithString:obj.imageURL]
                                      placeholderImage:[UIImage imageNamed:@"pic_jiazaizhogn.png"]
                                             completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL){
                                                 if (!image) {
                                                     [myCell.imageVPhoto setImage:[UIImage imageNamed:@"pic_jiazaishibai.png"]];
                                                 }
                                             }];
            }
                break;
            default:
                break;
        }

    }
    

    
    return myCell;
    
}


- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView
                        layout:(UICollectionViewLayout*)collectionViewLayout
        insetForSectionAtIndex:(NSInteger)section
{
    return self.edgeInset;
}


- (void)tapProfileImage:(UITapGestureRecognizer *)gestureRecognizer{
    
    UIImageView *tableGridImage = (UIImageView*)gestureRecognizer.view;
    NSInteger index = tableGridImage.tag;
    
    ImageBrowserObj *obj = self.arrContents[index];
    if (obj.itemType == ImageItemTypeAddButton) {
        
        if (_delegate &&
            [_delegate respondsToSelector:@selector(imageBrowserDidClickAddPicsButton:)]) {
            [_delegate imageBrowserDidClickAddPicsButton:self];
        }
        
    }else if (obj.itemType == ImageItemTypeImage) {
        
        NSMutableArray *photos = [NSMutableArray array];
        MWPhoto *photo;
        for (ImageBrowserObj *imageObj in _arrContents) {
            if (imageObj.itemType == ImageItemTypeAddButton || imageObj.itemType == ImageItemTypeDefault) {
                continue;
            }
            
            if (imageObj.imageSavedData) {
                photo = [MWPhoto photoWithImage:[UIImage imageWithData:imageObj.imageSavedData]];
            }else {
                switch (imageObj.sourceType) {
                    case ImageSourceTypeBundle:
                    {
                        UIImage *image = [UIImage imageNamed:imageObj.imageName];
                        photo = [MWPhoto photoWithImage:image];
                    }
                        break;
                    case ImageSourceTypeFilePath:
                    {
                        UIImage *image = [UIImage imageWithContentsOfFile:imageObj.imagePath];
                        photo = [MWPhoto photoWithImage:image];
                    }
                        break;
                    case ImageSourceTypeWebURL:
                    {
                        photo = [MWPhoto photoWithURL:[NSURL URLWithString:imageObj.imageURL]];
                    }
                        break;
                        
                    default:
                        break;
                }
            }
            
            [photos addObject:photo];
            
        }
        self.photos = photos;
        
        // 2.显示相册
        // Create browser
        MWPhotoBrowser *browser = [[MWPhotoBrowser alloc] initWithDelegate:self];
        browser.displayActionButton = NO;
        browser.displayNavArrows = YES;
        browser.displaySelectionButtons = NO;
        browser.alwaysShowControls = NO;
        browser.zoomPhotosToFill = YES;
#if __IPHONE_OS_VERSION_MIN_REQUIRED < __IPHONE_7_0
        browser.wantsFullScreenLayout = YES;
#endif
        browser.enableGrid = NO;
        browser.startOnGrid = NO;
        browser.enableSwipeToDismiss = YES;
        [browser setCurrentPhotoIndex:index];
        
        BaseNavigationController *nc = [[BaseNavigationController alloc] initWithRootViewController:browser];
        nc.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
        [self.vcImagePickerPrensentFrom?:self presentViewController:nc animated:YES completion:nil];
        
    }else {
    
    }    
    
}

- (void)addImageWithImageBrowserPhotoSource:(ImageBrowserPhotoSource)sourceType
{
    isAddImageAction = YES;
    
    BaseImagePickerController *imagePickerController = [[BaseImagePickerController alloc] init];
    
    if (sourceType == ImageBrowserPhotoSourceCamera
        && ![UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
        [UIApplication showAlertViewWithTitle:@"警告" message:@"您的设备不支持拍照功能。" delegate:nil tag:0 cancelButtonTitle:@"了解" otherButtonTitles:nil, nil];
        return;
    }
    
    if (sourceType == ImageBrowserPhotoSourceAlbum
        && ![UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeSavedPhotosAlbum]) {
        [UIApplication showAlertViewWithTitle:@"警告" message:@"您的设备不支持相册选图。" delegate:nil tag:0 cancelButtonTitle:@"了解" otherButtonTitles:nil, nil];
        return;
    }
    
    if (sourceType == ImageBrowserPhotoSourceLibrary
        && ![UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary]) {
        [UIApplication showAlertViewWithTitle:@"警告" message:@"您的设备不支持资源库选图。" delegate:nil tag:0 cancelButtonTitle:@"了解" otherButtonTitles:nil, nil];
        return;
    }
    
    if (sourceType == ImageBrowserPhotoSourceAsset) {
        
        NSMutableArray *arrPhotos = [NSMutableArray array];
        NSMutableArray *arrThumbs = [NSMutableArray array];
        @synchronized(_assets) {
            NSMutableArray *copy = [_assets copy];
            for (ALAsset *asset in copy) {
                [arrPhotos addObject:[MWPhoto photoWithURL:asset.defaultRepresentation.url]];
                [arrThumbs addObject:[MWPhoto photoWithImage:[UIImage imageWithCGImage:asset.thumbnail]]];
            }
        }
        
        self.photos = arrPhotos;
        self.thumbs = arrThumbs;
        // 2.显示相册
        // Create browser
        MWPhotoBrowser *browser = [[MWPhotoBrowser alloc] initWithDelegate:self];
        browser.displayActionButton = NO;
        browser.displayNavArrows = YES;
        browser.displaySelectionButtons = YES;
        browser.alwaysShowControls = NO;
        browser.zoomPhotosToFill = YES;
#if __IPHONE_OS_VERSION_MIN_REQUIRED < __IPHONE_7_0
        browser.wantsFullScreenLayout = YES;
#endif
        browser.enableGrid = YES;
        browser.startOnGrid = YES;
        browser.enableSwipeToDismiss = YES;
        [browser setCurrentPhotoIndex:0];
        
        BaseNavigationController *nc = [[BaseNavigationController alloc] initWithRootViewController:browser];
        nc.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
        [self.vcImagePickerPrensentFrom?:self presentViewController:nc animated:YES completion:nil];
        
        // Reset selections
        if (browser.displaySelectionButtons) {
            _selections = [NSMutableArray new];
            for (int i = 0; i < _photos.count; i++) {
                [_selections addObject:[NSNumber numberWithBool:NO]];
            }
        }


    }else {
        
        if (sourceType == ImageBrowserPhotoSourceCamera) {
            imagePickerController.sourceType = UIImagePickerControllerSourceTypeCamera;
        }else if (sourceType == ImageBrowserPhotoSourceAlbum) {
            imagePickerController.allowsEditing = NO;
            imagePickerController.sourceType = UIImagePickerControllerSourceTypeSavedPhotosAlbum;
        }else if (sourceType == ImageBrowserPhotoSourceLibrary) {
            imagePickerController.allowsEditing = NO;
            imagePickerController.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        }
        imagePickerController.delegate = self;
        [self.vcImagePickerPrensentFrom?:self presentViewController:imagePickerController
                                                           animated:YES
                                                         completion:nil];
        

    }
    
    
}

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    [[self nextResponder] touchesBegan:touches withEvent:event];
    
    [self.view endEditing:YES];
}

- (void)btnBackClick:(id)sender
{
    NSMutableArray *arrSelectImages = [NSMutableArray array];
    
    for (ImageBrowserObj *obj in _arrContents) {
        if (obj.itemType == ImageItemTypeImage) {
            [arrSelectImages addObject:obj];
        }
    }
    if (_delegate
        && [_delegate respondsToSelector:@selector(imageBrowser:didSelectImages:)])
    {
        [_delegate imageBrowser:self didSelectImages:arrSelectImages];
    }
    
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)didLongGestureTapedImageCell:(ImageBrowserCell *)cell
{
    ImageBrowserObj *obj = self.arrContents[cell.tag];
    obj.isShaking = YES;
    
}

- (void)didStopShaking:(ImageBrowserCell *)cell
{
    ImageBrowserObj *obj = self.arrContents[cell.tag];
    obj.isShaking = NO;
}

- (void)deletePhoto:(UIButton *)sender
{
    UIAlertView *alert=[[UIAlertView alloc] initWithTitle:@"删除图片" message:@"确认删除图片？" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"删除", nil];
    alert.tag=sender.tag;
    [alert show];
//    ImageBrowserObj *obj = self.arrContents[sender.tag];
//    [self.arrDeletedImages addObject:obj.imageId];
//     [_arrContents removeObject:obj];
//    if (_delegate && [_delegate respondsToSelector:@selector(imageBrowser:didDeleteImages:)]) {
//       [_delegate imageBrowser:self didDeleteImages:self.arrDeletedImages];
//    }
//    [self.collectionView reloadData];
}
-(void)alertView:(UIAlertView*)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
        if(buttonIndex==1)
        {
            ImageBrowserObj *obj = self.arrContents[alertView.tag];
            [self.arrDeletedImages addObject:obj.imageId];
            
            
     
            [_arrContents removeObject:obj];
           
            if (_delegate && [_delegate respondsToSelector:@selector(imageBrowser:didDeleteImages:)]) {
                [_delegate imageBrowser:self didDeleteImages:self.arrDeletedImages];
            }
            
            
            [self.collectionView reloadData];
        }
}





#pragma mark =============  UIImagePickerController Delegate  =============

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    [picker dismissViewControllerAnimated:YES completion:nil];

    UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];
    
    //设置image的尺寸
    CGSize imagesize = image.size;
    imagesize.height /= 2;
    imagesize.width /= 2;
    //对图片大小进行压缩--
    image = [image reSizeImagetoSize:imagesize];
    
    if (image) {
        ImageBrowserObj *detailObj = [[ImageBrowserObj alloc] init];
        NSString *imageId = [DataMgr stringFromDate:[NSDate date] format:@"yyyyMMddHHmmss"];
        detailObj.imageId = imageId;
        detailObj.isDeletable = YES;
        detailObj.sourceType = ImageSourceTypeFilePath;
        detailObj.imagePath = [NSString stringWithFormat:@"%@/%@.jpg", kImageCachePath, imageId];
        detailObj.imageName = [NSString stringWithFormat:@"%@.jpg", imageId];
        detailObj.imageSavedData = UIImageJPEGRepresentation(image, 0.032);
        [self.arrContents insertObject:detailObj atIndex:self.arrContents.count-1];
    }
    
    NSMutableArray *arrSelectImages = [NSMutableArray array];
    for (int i = 0; i<_arrContents.count-1; i++) {
        [arrSelectImages addObject:_arrContents[i]];
    }
    self.selectedImages = arrSelectImages;
    if (_delegate
        && [_delegate respondsToSelector:@selector(imageBrowser:didSelectImages:)]) {
        [_delegate imageBrowser:self didSelectImages:arrSelectImages];
    }
    
    [self.collectionView reloadData];
    
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
    [picker dismissViewControllerAnimated:YES completion:nil];
}

#pragma mark - MWPhotoBrowserDelegate

- (NSUInteger)numberOfPhotosInPhotoBrowser:(MWPhotoBrowser *)photoBrowser {
    return _photos.count;
}

- (id <MWPhoto>)photoBrowser:(MWPhotoBrowser *)photoBrowser photoAtIndex:(NSUInteger)index {
    if (index < _photos.count)
        return [_photos objectAtIndex:index];
    return nil;
}

- (id <MWPhoto>)photoBrowser:(MWPhotoBrowser *)photoBrowser thumbPhotoAtIndex:(NSUInteger)index {
    if (index < _thumbs.count)
        return [_thumbs objectAtIndex:index];
    return nil;
}

//- (MWCaptionView *)photoBrowser:(MWPhotoBrowser *)photoBrowser captionViewForPhotoAtIndex:(NSUInteger)index {
//    MWPhoto *photo = [self.photos objectAtIndex:index];
//    MWCaptionView *captionView = [[MWCaptionView alloc] initWithPhoto:photo];
//    return [captionView autorelease];
//}

//- (void)photoBrowser:(MWPhotoBrowser *)photoBrowser actionButtonPressedForPhotoAtIndex:(NSUInteger)index {
//    DLog(@"ACTION!");
//}

- (void)photoBrowser:(MWPhotoBrowser *)photoBrowser didDisplayPhotoAtIndex:(NSUInteger)index {
    DLog(@"Did start viewing photo at index %lu", (unsigned long)index);
}

- (BOOL)photoBrowser:(MWPhotoBrowser *)photoBrowser isPhotoSelectedAtIndex:(NSUInteger)index {
    return [[_selections objectAtIndex:index] boolValue];
}

- (NSString *)photoBrowser:(MWPhotoBrowser *)photoBrowser titleForPhotoAtIndex:(NSUInteger)index {
    return [NSString stringWithFormat:@"%@ %lu", NSLocalizedString(@"Photo", nil), (unsigned long)index+1];
}

- (void)photoBrowser:(MWPhotoBrowser *)photoBrowser photoAtIndex:(NSUInteger)index selectedChanged:(BOOL)selected {
    [_selections replaceObjectAtIndex:index withObject:[NSNumber numberWithBool:selected]];
    DLog(@"Photo at index %lu selected %@", (unsigned long)index, selected ? @"YES" : @"NO");
}

- (void)photoBrowserDidFinishModalPresentation:(MWPhotoBrowser *)photoBrowser {
    // If we subscribe to this method we must dismiss the view controller ourselves
    DLog(@"Did finish modal presentation");
    
    if (self.photoSource == ImageBrowserPhotoSourceAsset && isAddImageAction) {
        for (int i = 0; i<_selections.count; i++) {
            
            BOOL isSelected = [_selections[i] boolValue];
            if (isSelected) {
                
                ALAsset *asset = _assets[i];
                CGImageRef imageRef = asset.defaultRepresentation.fullResolutionImage;
                UIImage *imageAsset = [UIImage imageWithCGImage:imageRef];
                
                ImageBrowserObj *detailObj = [[ImageBrowserObj alloc] init];
                NSString *imageName = [[asset.defaultRepresentation.url description] lastPathComponent];
                detailObj.imageId = [[imageName componentsSeparatedByCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@"=&"]] objectAtIndex:1];
                detailObj.sourceType = ImageSourceTypeFilePath;
                detailObj.imagePath = [NSString stringWithFormat:@"%@/%@.jpg", kImageCachePath, detailObj.imageId];
                detailObj.imageName = [NSString stringWithFormat:@"%@.jpg", detailObj.imageId];
                detailObj.imageSavedData = UIImageJPEGRepresentation(imageAsset, 0.032);
                [self.arrContents insertObject:detailObj atIndex:self.arrContents.count-1];
            }

        }
    }
    NSMutableArray *arrSelectImages = [NSMutableArray array];
    
    for (ImageBrowserObj *obj in _arrContents) {
        if (obj.itemType == ImageItemTypeImage) {
            [arrSelectImages addObject:obj];
        }
    }
    if (_delegate
        && [_delegate respondsToSelector:@selector(imageBrowser:didSelectImages:)]) {
        [_delegate imageBrowser:self didSelectImages:arrSelectImages];
    }
    
    [self.collectionView reloadData];
    
    isAddImageAction = NO;
    
    [self.vcImagePickerPrensentFrom?:self dismissViewControllerAnimated:YES completion:nil];
}

#pragma mark - Load Assets

- (void)loadAssets {
    
    // Initialise
    _assets = [NSMutableArray new];
    _assetLibrary = [[ALAssetsLibrary alloc] init];
    
    // Run in the background as it takes a while to get all assets from the library
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        
        NSMutableArray *assetGroups = [[NSMutableArray alloc] init];
        NSMutableArray *assetURLDictionaries = [[NSMutableArray alloc] init];
        
        // Process assets
        void (^assetEnumerator)(ALAsset *, NSUInteger, BOOL *) = ^(ALAsset *result, NSUInteger index, BOOL *stop) {
            if (result != nil) {
                if ([[result valueForProperty:ALAssetPropertyType] isEqualToString:ALAssetTypePhoto]) {
                    [assetURLDictionaries addObject:[result valueForProperty:ALAssetPropertyURLs]];
                    NSURL *url = result.defaultRepresentation.url;
                    [_assetLibrary assetForURL:url
                                   resultBlock:^(ALAsset *asset) {
                                       if (asset) {
                                           @synchronized(_assets) {
                                               [_assets addObject:asset];
                                               if (_assets.count == 1) {
                                                   // Added first asset so reload data
                                               }
                                           }
                                       }
                                   }
                                  failureBlock:^(NSError *error){
                                      NSLog(@"operation was not successfull!");
                                  }];
                    
                }
            }
        };
        
        // Process groups
        void (^ assetGroupEnumerator) (ALAssetsGroup *, BOOL *) = ^(ALAssetsGroup *group, BOOL *stop) {
            if (group != nil) {
                [group enumerateAssetsWithOptions:NSEnumerationReverse usingBlock:assetEnumerator];
                [assetGroups addObject:group];
            }
        };
        
        // Process!
        [self.assetLibrary enumerateGroupsWithTypes:ALAssetsGroupAll
                                         usingBlock:assetGroupEnumerator
                                       failureBlock:^(NSError *error) {
                                           NSLog(@"There is an error");
                                       }];
        
    });
    
}


#pragma mark =============  LazyLoad Properties  =============

- (UICollectionView *)collectionView
{
    if (!_collectionView) {
        UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
        flowLayout.itemSize = self.itemSize;
        [flowLayout setScrollDirection:UICollectionViewScrollDirectionVertical];
        self.collectionView = [[UICollectionView alloc] initWithFrame:self.view.bounds collectionViewLayout:flowLayout];
        _collectionView.delegate = self;
        _collectionView.dataSource = self;
        _collectionView.backgroundColor = [UIColor clearColor];
        [self.collectionView registerClass:[ImageBrowserCell class]
                forCellWithReuseIdentifier:@"ImageBrowserCell"];
        [self.view addSubview:_collectionView];
    }
    return _collectionView;
}

- (NSMutableArray *)photos
{
    if (!_photos) {
        self.photos = [NSMutableArray array];
    }
    return _photos;
}

- (NSMutableArray *)thumbs
{
    if (!_thumbs) {
        self.thumbs = [NSMutableArray array];
    }
    return _thumbs;
}

- (NSMutableArray *)arrDeletedImages
{
    if (!_arrDeletedImages) {
        self.arrDeletedImages = [NSMutableArray array];
    }
    return _arrDeletedImages;
}

@end

@implementation ImageBrowserObj

- (void)dealloc
{
    self.imageId = nil;
    self.imageName = nil;
    self.imagePath = nil;
    self.imageURL = nil;
}
//
//- (NSData *)imageSavedData
//{
//    if (!_imageSavedData) {
//        UIImage *imageUpload = [DataMgr imageWithImagePath:self.imageLocalPath scaledToSize:kCommonImageSize];
//        self.imageSavedData = UIImageJPEGRepresentation(imageUpload, 0.032);//压缩
//    }
//    return _imageSavedData;
//}

@end
