//
//  PhotoPreviewViewController.m
//  隐私保护
//
//  Created by xd h on 2023/11/11.
//

#import "PhotoPreviewViewController.h"
#import "TZPhotoPreviewCell.h"
#import "photoPreViewBottomView.h"
#import "uploadFileRecordViewController.h"

@interface PhotoPreviewViewController ()<UICollectionViewDataSource,UICollectionViewDelegate,UICollectionViewDelegateFlowLayout,UIScrollViewDelegate>
@property (strong, nonatomic) UIButton *selectButton;
@property (strong, nonatomic) UICollectionView *photoPreviewCollectionV;
@property (strong, nonatomic) photoPreViewBottomView *photoPreViewBottomV;

@property (assign, nonatomic) BOOL canSetCurrentIndex;//


@property (strong, nonatomic)TZVideoPreviewCell * curCell;
@end

@implementation PhotoPreviewViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    [self.view setBackgroundColor:[UIColor blackColor]];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(videoPreviewCellDidPlayerFun) name:@"TZ_VIDEO_PLAY_NOTIFICATION" object:nil];
    
    
    [self.toolBar setHidden:YES];
    [self.navigationBar setHidden:YES];
    [self.navBarBGView setHidden:NO];
    
    [self setupPhotoPreviewNavBarView];
    //列表view
    [self setupPhotoPreviewCollectionView];
    [self setupPhotoPreViewBottomView];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear: animated];
    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent];
    
    //[self.photoPreviewCollectionV reloadData];
    
    if (_currentIndex >= 0) {
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            self->_canSetCurrentIndex = YES;
            [self.photoPreviewCollectionV setContentOffset:CGPointMake(SCREEN_W * self.currentIndex, 0) animated:NO];
        });
    }
    
    [self refreshNaviBarAndBottomBarState];
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    ///黑色
    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleDefault];
    
    [UIApplication sharedApplication].statusBarHidden = NO;
    [self.curCell pausePlayerAndShowNaviBar];
}

- (void)backBtnPressed{
    [super backBtnPressed];
    
    if(_changeSelectIndex){
        _changeSelectIndex(_indexPathsForSelectedItems);
    }
}

#pragma mark 点击选中按钮
- (void)didClickButtonFun:(UIButton*)but
{
    but.selected = !but.selected;
    
    [self handlCellSelectFun];
}

#pragma mark 处理点击选中相关
- (void)handlCellSelectFun
{
    
    TZAssetModel *model = self.assets[_currentIndex];
    
    //超出最大限制
    if (self.indexPathsForSelectedItems.count >= self.maximumNumberOfSelection ) {
        return;
    }
    
    //取消选中
    if ([self.indexPathsForSelectedItems containsObject:model]) {
        [self.indexPathsForSelectedItems removeObject:model];
        model.isSelected = NO;
    }
    else{//选中
        [self.indexPathsForSelectedItems addObject:model];
        model.isSelected = YES;
    
        if(!model.imageData)
        {
            [[PHImageManager defaultManager] requestImageDataForAsset:model.asset options:nil resultHandler:^(NSData * _Nullable imageData, NSString * _Nullable dataUTI, UIImageOrientation orientation, NSDictionary * _Nullable info) {
                    // 直接得到最终的 NSData 数据
                    if (imageData) {
                        //model.imageData = imageData;
                        model.totalBytes = [imageData length];
                    }
                if(model.type != TZAssetModelMediaTypeVideo){
                    [self setDataToBottomViewFun];
                }
            }];
            
            if(model.type == TZAssetModelMediaTypeVideo){
                
                PHVideoRequestOptions *options = [[PHVideoRequestOptions alloc] init];
                options.version = PHVideoRequestOptionsVersionOriginal;
                [[PHImageManager defaultManager] requestAVAssetForVideo:model.asset options:options resultHandler:^(AVAsset *asset, AVAudioMix *audioMix, NSDictionary *info) {
                    if ([asset isKindOfClass:[AVURLAsset class]]) {
                        
                        AVURLAsset* urlAsset = (AVURLAsset*)asset;
                        NSData *videoData = [NSData dataWithContentsOfURL:urlAsset.URL];
//                        NSNumber *size;
//                        [urlAsset.URL getResourceValue:&size forKey:NSURLFileSizeKey error:nil];
//                        NSLog(@"size is %f",[size floatValue]/(1024.0*1024.0));
                     
                        
                        //model.videoData = videoData;
                        model.totalBytes = [videoData length];
                        [self setDataToBottomViewFun];
                 }
                }];

            }

        }
    }
    
    
    [self setDataToBottomViewFun];
    //[self refreshNaviBarAndBottomBarState];
}

#pragma mark 同步数据到底部
- (void)setDataToBottomViewFun
{
    mainBlock(^{
        self.photoPreViewBottomV.indexPathsForSelectedItems = self.indexPathsForSelectedItems;
    });
    
}

#pragma mark 刷新导航栏的UI
- (void)refreshNaviBarAndBottomBarState
{
    self.titleLabel.text = [[NSString alloc] initWithFormat:@"%ld/%ld",(_currentIndex+1),_assets.count];
    
    TZAssetModel *model = self.assets[_currentIndex];
    
    self.selectButton.selected = model.isSelected;
}

- (void)setupPhotoPreviewNavBarView
{
    [self.backBtn setImage:[UIImage imageNamed:@"icon_white_back"] forState:UIControlStateNormal];
    self.navBarBGView.backgroundColor = [UIColor blackColor];
    self.titleLabel.textColor = [UIColor whiteColor];
    
    UIButton *but = [[UIButton alloc] init];
    [but setImage:[UIImage imageNamed:@"upload_file_uncheck"] forState:UIControlStateNormal];
    [but setImage:[UIImage imageNamed:@"upload_file_check"] forState:UIControlStateSelected];
    [but addTarget:self action:@selector(didClickButtonFun:) forControlEvents:UIControlEventTouchUpInside];
    [self.navBarBGView addSubview:but];

    self.selectButton = but;
    
    [but mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.mas_equalTo(-15);
        make.width.mas_equalTo(40);
        make.height.mas_equalTo(40);
        make.centerY.equalTo(self.titleLabel.mas_centerY).offset(0.f);
       
    }];
}
- (void)setupPhotoPreviewCollectionView
{
    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
    [flowLayout setScrollDirection:UICollectionViewScrollDirectionHorizontal];
    
    UICollectionView *collectionView = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:flowLayout];
    collectionView.dataSource = self;
    collectionView.delegate = self;
    collectionView.translatesAutoresizingMaskIntoConstraints = NO;
    collectionView.pagingEnabled = YES;
    collectionView.showsVerticalScrollIndicator = NO;
    collectionView.showsHorizontalScrollIndicator = NO;
    [self.view insertSubview:collectionView atIndex:0];
    collectionView.backgroundColor = [UIColor blackColor];
    
    
    [collectionView registerClass:[TZPhotoPreviewCell class] forCellWithReuseIdentifier:@"TZPhotoPreviewCell"];
    [collectionView registerClass:[TZPhotoPreviewCell class] forCellWithReuseIdentifier:@"TZPhotoPreviewCellGIF"];
    [collectionView registerClass:[TZVideoPreviewCell class] forCellWithReuseIdentifier:@"TZVideoPreviewCell"];
    [collectionView registerClass:[TZGifPreviewCell class] forCellWithReuseIdentifier:@"TZGifPreviewCell"];
    
    self.photoPreviewCollectionV = collectionView;
    
    [collectionView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(0);
        make.right.mas_equalTo(0);
        make.bottom.mas_equalTo(-(60 + safeArea));
        make.top.equalTo(self.navBarBGView.mas_bottom).offset(0.f);
    }];
    

}

- (void)setupPhotoPreViewBottomView
{
    photoPreViewBottomView * bottomView = [[photoPreViewBottomView alloc] init];
    [self.view addSubview:bottomView];
    self.photoPreViewBottomV = bottomView;
    
    self.photoPreViewBottomV.availableStorage = _availableStorage;
    [self setDataToBottomViewFun];
    
    [bottomView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(0);
        make.right.mas_equalTo(0);
        make.bottom.mas_equalTo(0);
        make.height.mas_equalTo((60 + safeArea));
    }];
    
    KWeakSelf
    bottomView.didClickUploadFile = ^{
        [weakSelf gotoUploadFileRecordFun];
    };
}
#pragma mark - UIScrollViewDelegate

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    CGFloat offSetWidth = scrollView.contentOffset.x;
    offSetWidth = offSetWidth +  (SCREEN_W * 0.5);
    
    NSInteger currentIndex = offSetWidth / (SCREEN_W + 20);
    if (currentIndex < _assets.count && _currentIndex != currentIndex && _canSetCurrentIndex)
    {
        _currentIndex = currentIndex;
        [self refreshNaviBarAndBottomBarState];
    }
    [[NSNotificationCenter defaultCenter] postNotificationName:@"photoPreviewCollectionViewDidScroll" object:nil];
}

#pragma mark - uicollectionDelegate
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return self.assets.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    
    TZAssetModel *model = self.assets[indexPath.row];
    
    TZAssetPreviewCell *cell;
    __weak typeof(self) weakSelf = self;
    if (model.type == TZAssetModelMediaTypeVideo) {
        cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"TZVideoPreviewCell" forIndexPath:indexPath];
        TZVideoPreviewCell *currentCell = (TZVideoPreviewCell *)cell;
        currentCell.iCloudSyncFailedHandle = ^(id asset, BOOL isSyncFailed) {
            model.iCloudFailed = isSyncFailed;
            //[weakSelf didICloudSyncStatusChanged:model];
        };
    } else if (model.type == TZAssetModelMediaTypePhotoGif) {
        cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"TZGifPreviewCell" forIndexPath:indexPath];
        TZGifPreviewCell *currentCell = (TZGifPreviewCell *)cell;
        currentCell.previewView.iCloudSyncFailedHandle = ^(id asset, BOOL isSyncFailed) {
            model.iCloudFailed = isSyncFailed;
            //[weakSelf didICloudSyncStatusChanged:model];
        };
    } else {
        NSString *reuseId = model.type == TZAssetModelMediaTypePhotoGif ? @"TZPhotoPreviewCellGIF" : @"TZPhotoPreviewCell";
        cell = [collectionView dequeueReusableCellWithReuseIdentifier:reuseId forIndexPath:indexPath];
        TZPhotoPreviewCell *photoPreviewCell = (TZPhotoPreviewCell *)cell;
        //photoPreviewCell.cropRect = _tzImagePickerVc.cropRect;
        //photoPreviewCell.allowCrop = _tzImagePickerVc.allowCrop;
        //photoPreviewCell.scaleAspectFillCrop = _tzImagePickerVc.scaleAspectFillCrop;
//        __weak typeof(_collectionView) weakCollectionView = _collectionView;
//        __weak typeof(photoPreviewCell) weakCell = photoPreviewCell;
//        [photoPreviewCell setImageProgressUpdateBlock:^(double progress) {
//            __strong typeof(weakSelf) strongSelf = weakSelf;
//            __strong typeof(weakCollectionView) strongCollectionView = weakCollectionView;
//            __strong typeof(weakCell) strongCell = weakCell;
//            strongSelf.progress = progress;
//            if (progress >= 1) {
//                if (strongSelf.isSelectOriginalPhoto) [strongSelf showPhotoBytes];
//                if (strongSelf.alertView && [strongCollectionView.visibleCells containsObject:strongCell]) {
//                    [strongSelf.alertView dismissViewControllerAnimated:YES completion:^{
//                        strongSelf.alertView = nil;
//                        [strongSelf doneButtonClick];
//                    }];
//                }
//            }
//        }];
        photoPreviewCell.previewView.iCloudSyncFailedHandle = ^(id asset, BOOL isSyncFailed) {
            model.iCloudFailed = isSyncFailed;
            //[weakSelf didICloudSyncStatusChanged:model];
        };
    }
    
    cell.model = model;
//    [cell setSingleTapGestureBlock:^{
//        __strong typeof(weakSelf) strongSelf = weakSelf;
//        //[strongSelf didTapPreviewCell];
//        
//        if([cell isKindOfClass:[TZVideoPreviewCell class]]){
//            weakSelf.curCell = cell;
//        }
//        
//    }];

    return cell;
}

- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section {
    return UIEdgeInsetsMake(0, 0, 0, 0);
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    CGFloat wh = SCREEN_H - CGRectGetMaxY(self.navBarBGView.frame) - (60 + safeArea);
    return CGSizeMake(SCREEN_W, wh);
}

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section {
    return 0.0;
}

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section {
    return 0.0;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{

}

#pragma mark 跳转上传记录
- (void)gotoUploadFileRecordFun
{
    [UIApplication sharedApplication].statusBarHidden = NO;
    
    uploadFileRecordViewController *vc = [uploadFileRecordViewController new];
    [self.navigationController pushViewController:vc animated:YES];
    
    [vc gotoUploadFile:_indexPathsForSelectedItems];
}

#pragma mark TZVideoPreviewCell视频播放
- (void)videoPreviewCellDidPlayerFun
{
    //[UIApplication sharedApplication].statusBarHidden = NO;
}


@end
