//
//  ZLPhotoBrowerView.m
//  SharedParking
//
//  Created by gui_huan on 2018/5/14.
//  Copyright © 2018年 tangshuanghui. All rights reserved.
//

#import "ZLPhotoBrowerView.h"
#import <Photos/Photos.h>
#import "ZLPhotoBrowerModel.h"
#import "ImageCell.h"
//#import "UIImage+TTAdditions.h"

typedef void(^Result)(NSData *fileData, NSString *fileName);
@interface ZLPhotoBrowerView()<UICollectionViewDelegate, UICollectionViewDataSource,UICollectionViewDelegateFlowLayout>


@end

@implementation ZLPhotoBrowerView


// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
    [self.collectionView reloadData];
}

- (instancetype)initWithCoder:(NSCoder *)aDecoder{
    self = [super initWithCoder:aDecoder];
    if (self) {
        [self addSubview:self.collectionView];
        float collectViewHeight = self.collectionView.collectionViewLayout.collectionViewContentSize.height;
        [self.collectionView mas_updateConstraints:^(MASConstraintMaker *make) {
            make.edges.equalTo(self);
            make.height.equalTo(@(collectViewHeight)).priorityLow();
        }];
    }
    return self;
}
- (instancetype)initWithFrame:(CGRect)frame{
    self = [super initWithFrame:frame];
    if (self) {
        [self addSubview:self.collectionView];
        float collectViewHeight = self.collectionView.collectionViewLayout.collectionViewContentSize.height;
        [self.collectionView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.edges.equalTo(self);
            make.height.equalTo(@(collectViewHeight)).priorityLow();
        }];
    }
    return self;
}


- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return self.photoModels.count + (self.photoModels.count == self.maxSelectCount ? 0 : 1);
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row >= self.photoModels.count) {
        ImageCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"ImageCell" forIndexPath:indexPath];
        cell.playImageView.hidden = YES;
        cell.imageView.image = ImageName(@"bd_camera");
        [cell.delButton setImage:nil forState:UIControlStateNormal];
        cell.delButton.hidden = YES;
        return cell;
    }else{
        ImageCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"ImageCell" forIndexPath:indexPath];
        cell.playImageView.hidden = !self.imageOrVideo;
        ZLPhotoBrowerModel *photoModel = self.photoModels[indexPath.row];
        cell.imageView.image = [UIImage imageWithData:photoModel.imageData];
        [cell.delButton setImage:ImageName(@"camrea_icon_delete") forState:UIControlStateNormal];
        cell.delButton.hidden = NO;
        WEAKSELF;
        cell.delBtnClick = ^{
            [wkSelf.photoModels removeObjectAtIndex:indexPath.row];
            [wkSelf.collectionView reloadData];
            if (wkSelf.selectedData) {
                StrongWeakSelf;
                stSelf.selectedData(stSelf.photoModels);
            }
        };
        return cell;
    }
    
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row == self.photoModels.count) {
        [[self getPas] showPreviewAnimated:YES];
    }else{
        [[self getPas] previewSelectedPhotos:[self getPhotoImages] assets:[self getPhotoAssets] index:indexPath.row isOriginal:YES];
    }
    
}

- (ZLPhotoActionSheet*)getPas {
    ZLPhotoActionSheet *photoAS = [[ZLPhotoActionSheet alloc]init];
    photoAS.configuration.maxSelectCount = self.maxSelectCount;
    photoAS.configuration.maxPreviewCount = 0;
    photoAS.configuration.allowSelectVideo = self.imageOrVideo;
    photoAS.configuration.allowSelectImage = !self.imageOrVideo;//默认imageOrVideo为NO
    photoAS.configuration.allowSelectOriginal = NO;
    photoAS.configuration.allowEditImage = NO;
    photoAS.configuration.allowTakePhotoInLibrary = NO;
    photoAS.configuration.allowRecordVideo = self.imageOrVideo;
    photoAS.configuration.exportVideoType = ZLExportVideoTypeMp4;
    photoAS.configuration.navTitleColor = SLColor(@"1677FF");
    
    photoAS.configuration.saveNewImageAfterEdit = NO;
    photoAS.sender = [UIViewController getCurrentShowVC];
    photoAS.arrSelectedAssets = photoAS.configuration.maxSelectCount > 1 ? [self getPhotoAssets] : nil;

    WEAKSELF;
    //选择回调
    [photoAS setSelectImageBlock:^(NSArray<UIImage *> * _Nonnull images, NSArray<PHAsset *> * _Nonnull assets, BOOL isOriginal) {
        //your codes
        StrongWeakSelf;
        stSelf.photoModels = nil;
        [stSelf postImageGetImageFileUrlWith:assets images:images];
        [stSelf.collectionView reloadData];
    }];
    //调用相册
    //    [photoAS showPhotoLibraryWithSender:self];
    //    [photoAS showPreviewAnimated:YES sender:self];
    return photoAS;
}

- (void)actionSheetAndClickSelPhotoLibrary:(BOOL)photoLibrary {
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        ZLPhotoActionSheet *sheet = [self getPas];
        [sheet showPreviewAnimated:NO sender:self.viewController];
        if (photoLibrary) {
            if ([sheet respondsToSelector:@selector(btnPhotoLibrary_Click:)]) {
                [sheet performSelector:@selector(btnPhotoLibrary_Click:) withObject:nil];
            }
        }else {
            if ([sheet respondsToSelector:@selector(btnCamera_Click:)]) {
                [sheet performSelector:@selector(btnCamera_Click:) withObject:nil];
            }
        }
        [sheet.subviews enumerateObjectsUsingBlock:^(__kindof UIView * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            obj.hidden = YES;
        }];
    });
}

- (void)postImageGetImageFileUrlWith:(NSArray<PHAsset *> *)assets images:(NSArray<UIImage *> *)images{

    if (assets.count > 0) {
        __block NSInteger count = 0;
        [assets enumerateObjectsUsingBlock:^(PHAsset * asset, NSUInteger idx, BOOL * _Nonnull stop) {
            
            [self.photoModels addObject:[[ZLPhotoBrowerModel alloc]init]];
            [self getImageFromPHAsset:asset Complete:^(NSData *fileData, NSString *fileName) {
                count ++;
                ZLPhotoBrowerModel *model = [[ZLPhotoBrowerModel alloc]init];
                model.imageName = [fileName stringByReplacingOccurrencesOfString:@".HEIC" withString:@".JPG"];
//                model.imageData = [UIImage compressImage:images[idx]];
                model.imageData = fileData;
                model.localIdentifier = asset.localIdentifier;
                [self.photoModels replaceObjectAtIndex:idx withObject:model];
                if (count == assets.count) {
                    if (self.selectedData) {
                        self.selectedData(self.photoModels);
                    }
                }
            }];
        }];
    }else{
        if (self.selectedData) {
            self.selectedData(self.photoModels);
        }
    }
    
}
#pragma mark -PHAssetMediaType 可选择图片类型
///asset.mediaType == PHAssetMediaTypeImage 
- (void)getImageFromPHAsset:(PHAsset *)asset Complete:(Result)result {
    __block NSData *data;
    PHAssetResource *resource = [[PHAssetResource assetResourcesForAsset:asset] firstObject];
    
    PHAssetMediaType mediaType = self.imageOrVideo ? PHAssetMediaTypeVideo:PHAssetMediaTypeImage;
    if (asset.mediaType == mediaType) {//PHAssetMediaTypeVideo视频
        PHImageRequestOptions *options = [[PHImageRequestOptions alloc] init];
        options.version = PHImageRequestOptionsVersionCurrent;
        options.deliveryMode = PHImageRequestOptionsDeliveryModeHighQualityFormat;
        options.synchronous = YES;
        [[PHImageManager defaultManager] requestImageDataForAsset:asset
                                                          options:options
                                                    resultHandler:
         ^(NSData *imageData,
           NSString *dataUTI,
           UIImageOrientation orientation,
           NSDictionary *info) {
             data = [NSData dataWithData:imageData];
         }];
    }
    __block BOOL isHEIF = NO;
    NSArray *resourceList = [PHAssetResource assetResourcesForAsset:asset];
    [resourceList enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        PHAssetResource *resource = obj;
        NSString *UTI = resource.uniformTypeIdentifier;
        if ([UTI isEqualToString:@"public.heif"] || [UTI isEqualToString:@"public.heic"]) {
            isHEIF = YES;
            *stop = YES;
        }
    }];
    if (result) {
        if (data.length <= 0) {
            result(nil, nil);
        } else {
            result(data, resource.originalFilename);
        }
    }
}

- (UICollectionView *)collectionView{
    if (!_collectionView) {
        _lineCount = 4;
        UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
        layout.minimumInteritemSpacing = 1.5;
        layout.minimumLineSpacing = 1.5;
        layout.sectionInset = UIEdgeInsetsMake(1, 1, 1, 1);
        _collectionView.collectionViewLayout = layout;
        _collectionView = [[UICollectionView alloc]initWithFrame:self.frame collectionViewLayout:layout];
        _collectionView.delegate = self;
        _collectionView.dataSource = self;
        _collectionView.backgroundColor = [UIColor whiteColor];
        _collectionView.scrollEnabled = NO;
        [_collectionView registerClass:NSClassFromString(@"ImageCell") forCellWithReuseIdentifier:@"ImageCell"];
    }
    return _collectionView;
}

- (void)setLineCount:(NSInteger)lineCount{
    _lineCount = lineCount;
    [self.collectionView reloadData];
}
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    CGFloat itemWidth = (CGRectGetWidth(self.bounds) - 10) / _lineCount;
    CGSize size = CGSizeMake(itemWidth, itemWidth - _lineCount * 2);
    return size;
}

- (NSMutableArray *)getPhotoImages{
    NSMutableArray *photoImages = [NSMutableArray new];
    for (ZLPhotoBrowerModel *zlModel in self.photoModels) {
        [photoImages addObject:[UIImage imageWithData:zlModel.imageData]];
    }
    return photoImages;
}

- (NSMutableArray *)getPhotoAssets{
    NSMutableArray *photoAssets = [NSMutableArray new];
    for (ZLPhotoBrowerModel *zlModel in self.photoModels) {
        PHFetchResult<PHAsset *> *arr = [PHAsset fetchAssetsWithLocalIdentifiers:@[zlModel.localIdentifier] options:nil];
        if (arr.count && arr.firstObject) {
            [photoAssets addObject:arr.firstObject];
        }
    }
    return photoAssets;
}


- (NSMutableArray<ZLPhotoBrowerModel *> *)photoModels{
    if (!_photoModels) {
        _photoModels = [NSMutableArray new];
    }
    return _photoModels;
}
- (void)setDataArray:(NSMutableArray<ZLPhotoBrowerModel *> *)dataArray{
    _dataArray = dataArray;
    self.photoModels = _dataArray;
    [self.collectionView reloadData];
    
    float collectViewHeight = self.collectionView.collectionViewLayout.collectionViewContentSize.height;
    [self.collectionView mas_updateConstraints:^(MASConstraintMaker *make) {
        make.height.equalTo(@(collectViewHeight)).priorityHigh();
    }];
}



- (void)dealloc{
    CheckRunWhere;
}
@end
