//
//  IWShowAndPickerViewController.m
//  GetAndSelectedAlbumImages
//
//  Created by goWhere on 15/11/23.
//  Copyright 漏 2015骞?Bruce. All rights reserved.
//

//  鑾峰彇灞忓箷瀹介珮
#define SCREEN_HEIGHT [UIScreen mainScreen].bounds.size.height
#define SCREEN_WIDTH  [UIScreen mainScreen].bounds.size.width



#import "IWShowAndPickerViewController.h"
#import "IWUIImageWithMoreInfo.h"
@import Photos;

@implementation MyCollectionCell{
    UIButton *_seleceButton;
}

static CGSize AssetGridThumbnailSize;

-(instancetype)initWithFrame:(CGRect)frame{
    self = [super initWithFrame:frame];
    if (self) {
        self.imageview = [[UIImageView alloc]initWithFrame:self.bounds];
        self.imageview.layer.masksToBounds = YES;
        [self.imageview setContentMode:UIViewContentModeScaleAspectFill];
        [self.contentView addSubview:self.imageview];

        //  鍦ㄥ彸涓婅娣诲姞閫夋嫨閿?        _seleceButton = [[UIButton alloc]initWithFrame:CGRectMake(self.frame.size.width * 3 / 4.0 - 3,
                                                                           3,
                                                                           self.frame.size.width / 4.0,
                                                                           self.frame.size.width / 4.0)];
        [_seleceButton setBackgroundColor:[UIColor colorWithRed:0 green:0 blue:0 alpha:0.1]];
        _seleceButton.layer.masksToBounds = YES;
        _seleceButton.layer.cornerRadius = _seleceButton.frame.size.width / 2.0;
        [_seleceButton setBackgroundImage:[UIImage imageNamed:@"iw_unselected"] forState:UIControlStateNormal];
        [_seleceButton setBackgroundImage:[UIImage imageNamed:@"iw_selected"] forState:UIControlStateSelected];
        _seleceButton.userInteractionEnabled = NO;
        [self.contentView addSubview:_seleceButton];
        
    }
    return self;
}

-(void)setIsChosse:(BOOL)isChosse{
    _isChosse = isChosse;
    _seleceButton.selected = isChosse;
}

@end

@interface IWShowAndPickerViewController ()<UICollectionViewDataSource,UICollectionViewDelegateFlowLayout,PHPhotoLibraryChangeObserver>

//  鍏ㄩ儴鐓х墖鏁版嵁婧愶紝
@property (nonatomic, strong) PHFetchResult *allPhotosResult;
//  缂撳瓨鍥剧墖鐨勬柟娉?@property (nonatomic, strong) PHCachingImageManager *cacheManager;
//  collectionView锛岀敤鏉ュ睍绀哄浘鐗?@property (nonatomic, strong) UICollectionView *collectionview;
//  鍥剧墖鏁扮粍
@property (nonatomic, strong) NSMutableArray *imageArray;
//  鏄剧ず鍥剧墖鏁伴噺鐨勮鍥?@property (nonatomic, strong) UIView *showAndSureBtnView;
//  宸查€夋嫨鐨勫浘鐗囨暟缁?@property (nonatomic, strong) NSMutableArray *selectedImagesArray;
//  鏄剧ず宸查€夊浘鐗囨暟閲忕殑label
@property (nonatomic, strong) UILabel *amountLabel;
//  閫夋嫨鍥剧墖瀹屾垚鍚庣殑纭畾鎸夐挳
@property (nonatomic, strong) UIButton *OKButton;


//  鏈€澶氳兘閫夊嚑寮犵収鐗?@property (nonatomic, assign) NSInteger maxAmount;

@end

@implementation IWShowAndPickerViewController{
    NSInteger NaviHeight;
}

//  鍒濆鍖?- (NSMutableArray *)imageArray
{
    if (!_imageArray) {
        _imageArray = [[NSMutableArray alloc]initWithCapacity:0];
    }
    return _imageArray;
}

-(NSMutableArray *)selectedImagesArray{
    if (!_selectedImagesArray) {
        _selectedImagesArray = [NSMutableArray arrayWithCapacity:0];
    }
    return _selectedImagesArray;
}

-(instancetype)initWithYouWantSelectedPhtotsAmount:(NSInteger)amount{
    self = [IWShowAndPickerViewController new];
    if (self) {
        NaviHeight = 0;
        //  濡傛灉浼犲叆鐨勬暟缁勫ぇ浜?锛屽垯寮哄埗鍙?.濡傛灉灏忎簬1锛屽垯寮哄埗涓?
        self.maxAmount = amount;
        if (amount > 9) {
            self.maxAmount = 9;
        }
        if (amount < 1) {
            self.maxAmount = 1;
        }

    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    self.navigationItem.title = @"鎵€鏈夌収鐗?;
    
    self.imageArray = [NSMutableArray arrayWithCapacity:0];
    
    //  鍒濆鍖?    self.cacheManager = [[PHCachingImageManager alloc]init];
        [[PHPhotoLibrary sharedPhotoLibrary] registerChangeObserver:self];
    
    //  鑾峰彇鍏ㄩ儴鍥剧墖锛屽苟鎸夋椂闂存帓搴?    if (self.photoResult.count == 0) {
        PHFetchOptions *allOptions = [[PHFetchOptions alloc]init];
        allOptions.sortDescriptors =  @[[NSSortDescriptor sortDescriptorWithKey:@"creationDate" ascending:YES]];
        self.allPhotosResult = [PHAsset fetchAssetsWithOptions:allOptions];
    }else{
        self.allPhotosResult = self.photoResult;
    }
    

    
    NSInteger count = self.allPhotosResult.count;
    for (int i= 0; i < count; i++) {
        [self.imageArray addObject:[NSNumber numberWithInt:0]];
    }
    //  鍒涘缓涓€涓猚ollectionView
    self.collectionview = [self createCollectionView];
    
    //  鍒涘缓涓€涓樉绀洪€夋嫨鏁伴噺鐨勮鍥?    self.showAndSureBtnView = [self selectedAmountAndSureButtonView];
    
    //  鍙充笂瑙掓坊鍔犲彇娑堟寜閽?    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithTitle:@"鍙栨秷" style:UIBarButtonItemStylePlain target:self action:@selector(dismissAction)];
}


- (void)photoLibraryDidChange:(PHChange *)changeInstance{
    
    dispatch_async(dispatch_get_main_queue(), ^{
        //    //  鑾峰彇鍏ㄩ儴鍥剧墖锛屽苟鎸夋椂闂存帓搴?        if (self.photoResult.count == 0) {
            PHFetchOptions *allOptions = [[PHFetchOptions alloc]init];
            allOptions.sortDescriptors =  @[[NSSortDescriptor sortDescriptorWithKey:@"creationDate" ascending:YES]];
            self.allPhotosResult = [PHAsset fetchAssetsWithOptions:allOptions];
        }else{
            self.allPhotosResult = self.photoResult;
        }
        for (int i= 0; i < self.allPhotosResult.count; i++) {
            [self.imageArray addObject:[NSNumber numberWithInt:0]];
        }
        NSLog(@"imagearray : %ld", self.imageArray.count);
        [self.collectionview reloadData];
        
    });
}


- (void)dealloc {
    [[PHPhotoLibrary sharedPhotoLibrary] unregisterChangeObserver:self];
}

//  杩斿洖
- (void)dismissAction{
    [self dismissViewControllerAnimated:YES completion:nil];
}

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

#pragma mark- 閫夋嫨鍥剧墖鐨勬暟閲?- (UIView *)selectedAmountAndSureButtonView{
    UIView *amountView = [[UIView alloc]initWithFrame:CGRectMake(0, SCREEN_HEIGHT, SCREEN_WIDTH, 44)];
    amountView.backgroundColor = [UIColor groupTableViewBackgroundColor];
    [self.view addSubview:amountView];
    
    
    //  娣诲姞纭畾鎸夐挳
    self.OKButton = [[UIButton alloc]initWithFrame:CGRectMake(amountView.frame.size.width * 3 / 8.0, 0, SCREEN_WIDTH / 4.0, 44)];
    [self.OKButton addTarget:self action:@selector(selectedOverAndCallback) forControlEvents:UIControlEventTouchUpInside];
    [amountView addSubview:self.OKButton];
    //  娣诲姞鏄剧ず鏁伴噺鐨刲abel
    self.amountLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, 22, 22)];
    self.amountLabel.backgroundColor = [UIColor greenColor];
    self.amountLabel.layer.masksToBounds = YES;
    self.amountLabel.layer.cornerRadius = self.amountLabel.frame.size.width / 2.0;
    self.amountLabel.font = [UIFont boldSystemFontOfSize:16];
    self.amountLabel.textColor = [UIColor whiteColor];
    self.amountLabel.textAlignment = NSTextAlignmentCenter;
    self.amountLabel.center = CGPointMake(self.OKButton.frame.size.width / 4.0, amountView.frame.size.height / 2.0);
    [self.OKButton addSubview:self.amountLabel];
    
    UILabel *nameLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH / 6.0, 25)];
    nameLabel.textColor = [UIColor greenColor];
    nameLabel.text = @"瀹屾垚";
    nameLabel.font = [UIFont boldSystemFontOfSize:16];
    nameLabel.textAlignment = NSTextAlignmentCenter;
    nameLabel.center = CGPointMake(self.OKButton.frame.size.width * 3 / 5.0, amountView.frame.size.height / 2.0);
    [self.OKButton addSubview:nameLabel];

    
    return amountView;
}

#pragma mark-  鐐瑰嚮纭畾鎸夐挳锛屼絾浼氶€夋嫨鐨勫浘鐗?- (void)selectedOverAndCallback{

   __block NSMutableArray *imagesArray = [NSMutableArray array];
    __block __weak IWShowAndPickerViewController *weakself = self;
    //  杞寲鍥剧墖
    //  鍒ゆ柇鏄粯璁ょ殑缂╃暐鍥捐繕鏄嚜瀹氫箟鐨勫昂瀵?    
    for (PHAsset *asset in self.selectedImagesArray) {
        __block BOOL isSmall = YES;
        __block UIActivityIndicatorView *indicator = [[UIActivityIndicatorView alloc]init];
        indicator.center = CGPointMake(SCREEN_WIDTH / 2.0f, SCREEN_HEIGHT / 2.0f);
        [indicator startAnimating];
        
        [[PHImageManager defaultManager] requestImageForAsset:asset
                                                   targetSize:AssetGridThumbnailSize
                                                  contentMode:PHImageContentModeAspectFit
                                                      options:nil
                                                resultHandler:^(UIImage * _Nullable result, NSDictionary * _Nullable info) {
//                                                    NSLog(@"--123---%f---------%f",result.size.width,result.size.height);

                                                    if (isSmall) {
                                                        //  绗竴娆℃槸缂╃暐鍥?                                                        NSLog(@"------缂╃暐鍥?----%@",result);
                                                        isSmall = NO;
                                                    }else{
                                                        //  鑾峰彇鎷嶇収鏃堕棿銆佺粡绾害淇℃伅
                                                        IWUIImageWithMoreInfo *imageMoreIno = [[IWUIImageWithMoreInfo alloc] initWithCGImage:[result CGImage]];
                                                        imageMoreIno.creationDate = asset.creationDate;
                                                        imageMoreIno.modificationDate = asset.modificationDate;
                                                        imageMoreIno.location = asset.location;
                                                        [imagesArray addObject:imageMoreIno];
                                                        isSmall = YES;
                                                    }

                                                    if (imagesArray.count == self.selectedImagesArray.count) {
//                                                        NSLog(@"-------444--------%@",imagesArray);
                                                        weakself.photosCallback(imagesArray);
                                                       
                                                        [weakself.view addSubview:indicator];
                                                        
                                                        [weakself dismissViewControllerAnimated:YES completion:^{
                                                            [indicator stopAnimating];
                                                        }];
                                                    }

        }];
        
    }
}




//  鍥炶皟鏂规硶
-(void)getSelectedPhotosBack:(PickerPhotosCallback)callback{
    self.photosCallback = callback;
}


//瑙嗗浘鏃嬭浆鏂瑰悜鍙戠敓鏀瑰彉鏃朵細鑷姩璋冪敤
-(void)willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration
{
    [self.collectionview removeFromSuperview];
    if (SCREEN_HEIGHT > SCREEN_WIDTH) {
        NaviHeight = 64;
    }else{
        NaviHeight = 40;
    }
    
    //  鍒涘缓涓€涓猚ollectionView
    self.collectionview = [self createCollectionView];
    self.showAndSureBtnView = nil;
    //  鍒涘缓涓€涓樉绀洪€夋嫨鏁伴噺鐨勮鍥?    self.showAndSureBtnView = [self selectedAmountAndSureButtonView];
}


#pragma mark- 鍒涘缓涓€涓猚ollectionView
- (UICollectionView *)createCollectionView{
    CGFloat imageSpace = 0.0;
    if (SCREEN_HEIGHT > SCREEN_WIDTH) {
        imageSpace = SCREEN_WIDTH / 150.0f;
    }else{
        imageSpace = SCREEN_HEIGHT / 100.0f;
    }
    
    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc]init];
    flowLayout.minimumInteritemSpacing = imageSpace;
    flowLayout.minimumLineSpacing = imageSpace;


    if (SCREEN_HEIGHT > SCREEN_WIDTH) {
        flowLayout.itemSize = CGSizeMake(SCREEN_WIDTH * 29 / 120.0f, SCREEN_WIDTH * 29 / 120.0f);
    } else {
        flowLayout.itemSize = CGSizeMake(SCREEN_HEIGHT * 29 / 120.0f, SCREEN_HEIGHT* 29 / 120.0f);
        flowLayout.minimumLineSpacing = 5;
    }
    
    UICollectionView *collectionview = [[UICollectionView alloc]initWithFrame:CGRectMake(0, NaviHeight, SCREEN_WIDTH, SCREEN_HEIGHT - NaviHeight) collectionViewLayout:flowLayout];
    collectionview.backgroundColor = [UIColor whiteColor];
    [collectionview registerClass:[MyCollectionCell class] forCellWithReuseIdentifier:@"myCell"];
    collectionview.dataSource = self;
    collectionview.delegate = self;
    [self.view addSubview:collectionview];
    
    CGFloat scale = [UIScreen mainScreen].scale;
    CGSize cellSize = flowLayout.itemSize;
    AssetGridThumbnailSize = CGSizeMake(cellSize.width * scale, cellSize.height * scale);
    
    return collectionview;
}

#pragma mark- collctionview delegate
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    
//    NSLog(@"---------%ld--------%@",self.allPhotosResult.count,self.allPhotosResult);
    
    return self.allPhotosResult.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView
                  cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    MyCollectionCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"myCell" forIndexPath:indexPath];
    if (!cell) {
        cell = [[MyCollectionCell alloc]init];
    }
    PHAsset *asset = self.allPhotosResult[indexPath.row];
    [self.cacheManager requestImageForAsset:asset
                                 targetSize:CGSizeZero
                                contentMode:PHImageContentModeAspectFit
                                    options:nil
                              resultHandler:^(UIImage * _Nullable result, NSDictionary * _Nullable info) {
        cell.imageview.image = result;
        cell.isChosse = [(NSNumber *)[self.imageArray objectAtIndex:indexPath.row] boolValue];
    }];
    return cell;
}

-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
     MyCollectionCell *cell = (id)[collectionView cellForItemAtIndexPath:indexPath];

    //  濡傛灉鍙€夋嫨涓€寮?    if (self.maxAmount == 1) {
        [self.selectedImagesArray addObject:self.allPhotosResult[indexPath.row]];
        [self selectedOverAndCallback];
    }else{
        //  澶氬紶閫夋嫨
        
        //  鍒ゆ柇鏄惁宸茬粡閫夋嫨瓒冲
        if (self.selectedImagesArray.count < self.maxAmount) {
            //  杩樻病閫夊锛屾帴鐫€鍡?            cell.isChosse = !cell.isChosse;
            if (cell.isChosse) {
                [self.selectedImagesArray addObject:self.allPhotosResult[indexPath.row]];
            }
            if (!cell.isChosse && self.selectedImagesArray.count > 0) {
                [self.selectedImagesArray removeObject:self.allPhotosResult[indexPath.row]];
            }
            
            if (self.selectedImagesArray.count > 0) {
                [UIView animateWithDuration:0.3 animations:^{
                    self.showAndSureBtnView.frame = CGRectMake(0, SCREEN_HEIGHT - 44, SCREEN_WIDTH, 44);
                    
                    //  collectionview澶у皬闅忕潃鏀瑰彉
                    self.collectionview.frame = CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT - 44);
                }];
            }else{
                [UIView animateWithDuration:0.3 animations:^{
                    self.showAndSureBtnView.frame = CGRectMake(0, SCREEN_HEIGHT, SCREEN_WIDTH, 44);
                    
                    //  collectionview澶у皬闅忕潃鏀瑰彉
                    self.collectionview.frame = CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT);
                }];
            }
            
            [self amountLabelAnimation];
            
            self.imageArray[indexPath.row] = [NSNumber numberWithBool:cell.isChosse];
            
        }else{      //  閫夊浜嗭紝涓嶈兘璧帮紝姝ゆ椂鑳藉彇娑堬紝涓嶈兘娣诲姞閫夋嫨  [NSString stringWithFormat:@"鏈€澶氬彧鑳介€夋嫨%ld寮?,self.maxAmount]
            if (!cell.isChosse) {
                UIAlertController *alertC = [UIAlertController alertControllerWithTitle:[NSString stringWithFormat:@"鏈€澶氬彧鑳介€夋嫨%ld寮?,(long )self.maxAmount]
                                                                                message:nil
                                                                         preferredStyle:UIAlertControllerStyleAlert];

                [alertC addAction:[UIAlertAction actionWithTitle:@"纭畾" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                    //  鍟ヤ篃涓嶅仛灏辫浜?                }]];
                [self presentViewController:alertC animated:YES completion:^{
                    
                }];
            }else{
                cell.isChosse = NO;
                //  姝ゆ椂鐐瑰嚮鐨勬槸閫変腑鐨勶紝鍑忓皯灏卞ソ浜?                [self.selectedImagesArray removeObject:self.allPhotosResult[indexPath.row]];
                if (self.selectedImagesArray.count == 0) {
                    [UIView animateWithDuration:0.3 animations:^{
                        self.showAndSureBtnView.frame = CGRectMake(0, SCREEN_HEIGHT, SCREEN_WIDTH, 44);
                    }];
                }
                [self amountLabelAnimation];
                
                self.imageArray[indexPath.row] = [NSNumber numberWithBool:cell.isChosse];
            }
        
        }
        
    }

}

//   鏁板瓧鍙樺寲鐨勫姩鎬佸睍绀?- (void)amountLabelAnimation{
    
    self.amountLabel.frame = CGRectMake(self.amountLabel.center.x, self.amountLabel.center.y, 0, 0);
    self.amountLabel.layer.cornerRadius = self.amountLabel.frame.size.width / 4.0;
    [UIView animateWithDuration:0.15 animations:^{
        self.amountLabel.frame = CGRectMake(0, 0, 22, 22);
        self.amountLabel.layer.cornerRadius = self.amountLabel.frame.size.width / 2.0;
        self.amountLabel.center = CGPointMake(self.OKButton.frame.size.width / 4.0, self.showAndSureBtnView.frame.size.height / 2.0);
        self.amountLabel.text = [NSString stringWithFormat:@"%ld",(long )self.selectedImagesArray.count];
    }];
    
    //      鏀惧皠鍙樻崲
    [UIView animateWithDuration:0.3 animations:^{
        self.amountLabel.transform = CGAffineTransformMakeScale(0.35, 0.35);
        self.amountLabel.transform = CGAffineTransformScale(self.amountLabel.transform, 3, 3);
    }];
}

@end
// 鐗堟潈灞炰簬鍘熶綔鑰?// http://code4app.com (cn) http://code4app.net (en)
// 鍙戝竷浠g爜浜庢渶涓撲笟鐨勬簮鐮佸垎浜綉绔? Code4App.com