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

#import "uploadImageOrVideoViewController.h"
#import <AssetsLibrary/AssetsLibrary.h>
#import <AVFoundation/AVFoundation.h>
#import "AJPhotoListView.h"
#import "AJPhotoGroupView.h"
#import "AJPhotoListCell.h"
#import "uploadFileBottomView.h"
#import "PhotoPreviewViewController.h"
#import "TZAssetModel+imageData.h"
#import "uploadFileRecordViewController.h"
#import "couldPhoneBaseInfoModel.h"

@interface uploadImageOrVideoViewController ()<AJPhotoGroupViewProtocol,UICollectionViewDataSource,UICollectionViewDelegate,UICollectionViewDelegateFlowLayout>

@property (strong, nonatomic) AJPhotoGroupView *photoGroupView;
@property (strong, nonatomic) UILabel *MytitleLabel;
@property (strong, nonatomic) UIImageView *selectTip;
@property (nonatomic) BOOL isNotAllowed;
@property (strong, nonatomic) UIView *bgMaskView;
@property (strong, nonatomic) AJPhotoListView *photoListView;
@property (strong, nonatomic) NSMutableArray *assets;
@property (strong, nonatomic) NSIndexPath *lastAccessed;
@property (strong, nonatomic) uploadFileBottomView *uploadFileBottomV;

//最多选择项
@property (nonatomic, assign) NSInteger maximumNumberOfSelection;

//最少选择项
@property (nonatomic, assign) NSInteger minimumNumberOfSelection;


//是否开启多选
@property (nonatomic, assign) BOOL multipleSelection;

@end

@implementation uploadImageOrVideoViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(getCouldPhoneBaseInfoFun:)  name:getCouldPhoneBaseInfoNotification  object:nil];
    
    [self.view setBackgroundColor:HWF5F7FAColor];
    
    [self.toolBar setHidden:YES];
    [self.navigationBar setHidden:YES];
    [self.navBarBGView setHidden:NO];
    
    [self initBaselUIFun];
    
    _isNotAllowed = YES;
    _maximumNumberOfSelection = 30;
    _minimumNumberOfSelection = 0;
    _multipleSelection = YES;
    
    if(!_selectionFilter)
    {
        _selectionFilter = [NSPredicate predicateWithValue:YES];
    }
    [self checkVideoAccessFun];
    
}

- (void)initBaselUIFun
{
    [self initNavHeadUIFun];
    
    //列表view
    [self setupPhotoListView];
    [self setupUploadFileBottomView];
    //相册分组
    [self setupGroupView];
}

- (void)initNavHeadUIFun
{
    //title
    UILabel *titleLabel = [[UILabel alloc] init];
    titleLabel.textAlignment = NSTextAlignmentCenter;
    titleLabel.font = [UIFont boldSystemFontOfSize:18.0];
    titleLabel.translatesAutoresizingMaskIntoConstraints = NO;
    [self.navBarBGView addSubview:titleLabel];

    self.MytitleLabel = titleLabel;
    
    //selectTipImageView
    UIImageView *selectTip = [[UIImageView alloc] init];
    selectTip.image = [UIImage imageNamed:@"upload_image_arrow"];
    selectTip.translatesAutoresizingMaskIntoConstraints = NO;
    [self.navBarBGView addSubview:selectTip];
    self.selectTip = selectTip;
    
    UIButton *tapBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    tapBtn.backgroundColor = [UIColor clearColor];
    tapBtn.translatesAutoresizingMaskIntoConstraints = NO;
    [tapBtn addTarget:self action:@selector(selectGroupAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.navBarBGView addSubview:tapBtn];
    
    [tapBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_equalTo(self.navBarBGView.mas_centerX);
        make.centerY.mas_equalTo(self.backBtn.mas_centerY);
        make.width.mas_equalTo(100);
        make.height.mas_equalTo(30);
    }];
    
    [self setTitleLabelText:@""];
    
    UIButton *rightBut = [[UIButton alloc] init];
    [rightBut setTitle:NSLocalizedString(@"File_upload_Record_select_all",nil) forState:UIControlStateNormal];
    [rightBut setTitle:NSLocalizedString(@"File_upload_cancel_select_all",nil) forState:UIControlStateSelected];
    [rightBut setTitleColor:[UIColor hwColor:@"#01B7EA" alpha:1.0] forState:UIControlStateNormal];
    rightBut.contentHorizontalAlignment = UIControlContentHorizontalAlignmentRight;
    [rightBut addTarget:self action:@selector(didClickSelectAllButton:) forControlEvents:UIControlEventTouchUpInside];
    
    [self.navBarBGView addSubview:rightBut];
    
    [rightBut mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.mas_equalTo(-20);
        make.centerY.mas_equalTo(self.backBtn.mas_centerY);
        make.width.mas_equalTo(100);
        make.height.mas_equalTo(30);
    }];
}

#pragma mark 设置相册标题
- (void)setTitleLabelText:(NSString*)title
{
    self.MytitleLabel.text = title;
    
    CGFloat curWidth = [title boundingRectWithSize:CGSizeMake(SCREEN_W, 30) options:(NSStringDrawingUsesLineFragmentOrigin) attributes:@{NSFontAttributeName:[UIFont boldSystemFontOfSize:18.f]} context:nil].size.width;
    
    curWidth += 20;
    //HLog(@"title w:%f",curWidth);
    [self.MytitleLabel mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_equalTo(self.navBarBGView.mas_centerX).offset(-10);
        make.centerY.mas_equalTo(self.backBtn.mas_centerY);
        make.width.mas_equalTo(curWidth);
        make.height.mas_equalTo(30);
    }];
    //self.MytitleLabel.backgroundColor = [UIColor greenColor];
    
    [self.selectTip mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(self.MytitleLabel.mas_right).offset(2);
        make.centerY.mas_equalTo(self.backBtn.mas_centerY);
        make.width.mas_equalTo(15);
        make.height.mas_equalTo(15);
    }];
}

#pragma mark 点击全选
- (void)didClickSelectAllButton:(UIButton*)but
{
    but.selected = !but.selected;
    
    if(but.selected){
        [self.indexPathsForSelectedItems removeAllObjects];
        
        for (TZAssetModel *model in self.assets) {
            [self didSelectModel:model];
        }
    }
    else{
        for (TZAssetModel *model in self.assets) {
             model.isSelected = NO;
        }
        [self.indexPathsForSelectedItems removeAllObjects];
    }
    
    [self refreshAllDataFun];
}

#pragma mark 判断手机相册权限
- (void)checkVideoAccessFun
{
    AVAuthorizationStatus authStatus =[AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
    //判断摄像头状态是否可用
    if(authStatus==AVAuthorizationStatusAuthorized){
        _isNotAllowed = NO;
    }else{
        NSLog(@"未开启相机权限，请前往设置中开启");
        [AVCaptureDevice requestAccessForMediaType:AVMediaTypeVideo completionHandler:^(BOOL granted) {
            if (granted){
                self->_isNotAllowed = NO;
//                mainBlock(^{
//
//                });
            }
        }];
    }
    
    //相册权限
    if (![[TZImageManager manager] authorizationStatusAuthorized]){
        [PHPhotoLibrary requestAuthorization:^(PHAuthorizationStatus status) {
            if(status == PHAuthorizationStatusAuthorized){
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    [self.photoGroupView setupGroup];
                    [self delayedSetPhotoGroupViewFrameFun];
                });
                
            }
        }];
    }
}

/**
 *  照片列表
 */
- (void)setupPhotoListView {
    AJPhotoListView *collectionView = [[AJPhotoListView alloc] init];
    collectionView.dataSource = self;
    collectionView.delegate = self;
    collectionView.translatesAutoresizingMaskIntoConstraints = NO;
    [self.view insertSubview:collectionView atIndex:0];
    self.photoListView = 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)setupUploadFileBottomView
{
    uploadFileBottomView *bottomView = [[uploadFileBottomView alloc] init];
    [self.view insertSubview:bottomView atIndex:0];
    self.uploadFileBottomV = bottomView;
    
    [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];
    };
}

/**
 *  相册
 */
- (void)setupGroupView {
    AJPhotoGroupView *photoGroupView = [[AJPhotoGroupView alloc] init];
    photoGroupView.my_delegate = self;
    photoGroupView.isPhotoType = _isPhotoType;
    [self.view insertSubview:photoGroupView belowSubview:self.navBarBGView];
    self.photoGroupView = photoGroupView;
    photoGroupView.hidden = YES;
    photoGroupView.translatesAutoresizingMaskIntoConstraints = NO;
    
    [self.photoGroupView setupGroup];
    
    [self delayedSetPhotoGroupViewFrameFun];
}

#pragma mark 延时设置photoGroupView frame
- (void)delayedSetPhotoGroupViewFrameFun
{
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        
        NSInteger maxCount = 6;
        if(self.photoGroupView.albumGroups.count < maxCount){
            maxCount = self.photoGroupView.albumGroups.count;
        }
        
        [self.photoGroupView mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.left.mas_equalTo(0);
            make.right.mas_equalTo(0);
            make.height.mas_equalTo(60.0 * maxCount);
            make.top.equalTo(self.navBarBGView.mas_bottom).offset(0.f);
        }];
    });
}

#pragma mark - 相册切换
- (void)selectGroupAction:(UIButton *)sender {
    
    //无权限
    if (self.isNotAllowed) {
        return;
    }

    if (self.photoGroupView.hidden) {
        [self bgMaskView];
        self.bgMaskView.hidden = NO;
        self.photoGroupView.hidden = NO;
        [UIView animateWithDuration:0.3 animations:^{
            CGRect rect = self.photoGroupView.frame;
            rect.origin.y = CGRectGetMaxY(self.navBarBGView.frame);
            self.photoGroupView.frame = rect;
            
            self.selectTip.transform = CGAffineTransformMakeRotation(M_PI);
        }];
    } else {
        [self hidenGroupView];
    }
}

- (void)hidenGroupView {
    //[self.bgMaskView removeFromSuperview];
    self.bgMaskView.hidden = YES;
    [UIView animateWithDuration:0.3 animations:^{
        CGRect rect = self.photoGroupView.frame;
        rect.origin.y = -SCREEN_H;
        self.photoGroupView.frame = rect;
        
        self.selectTip.transform = CGAffineTransformIdentity;
    }completion:^(BOOL finished) {
        self.photoGroupView.hidden = YES;
    }];
}


#pragma mark - 遮罩背景
- (UIView *)bgMaskView {
    if (_bgMaskView == nil) {
        UIView *bgMaskView = [[UIView alloc] init];
        bgMaskView.alpha = 0.5;
        bgMaskView.translatesAutoresizingMaskIntoConstraints = NO;
        bgMaskView.backgroundColor = [UIColor blackColor];
        //[self.view insertSubview:bgMaskView aboveSubview:self.photoListView];
        [self.view insertSubview:bgMaskView belowSubview:self.photoGroupView];
        
        bgMaskView.userInteractionEnabled = YES;
        [bgMaskView addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapBgMaskView:)]];
        _bgMaskView = bgMaskView;
        
        [bgMaskView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.mas_equalTo(0);
            make.right.mas_equalTo(0);
            make.bottom.mas_equalTo(0);
            make.top.equalTo(self.navBarBGView.mas_bottom).offset(0.f);
        }];
    }
   
    return _bgMaskView;
}

- (void)tapBgMaskView:(UITapGestureRecognizer *)sender {
    if (!self.photoGroupView.hidden) {
        [self hidenGroupView];
    }
}


#pragma mark - BoPhotoGroupViewProtocol
- (void)didSelectGroup:(TZAlbumModel *)model {
    [self loadAssets:model];
    [self setTitleLabelText:model.name];
    [self hidenGroupView];
}

//加载图片
- (void)loadAssets:(TZAlbumModel *)model {
    [self.indexPathsForSelectedItems removeAllObjects];
    [self.assets removeAllObjects];

    [[TZImageManager manager] getAssetsFromFetchResult:model.result completion:^(NSArray<TZAssetModel *> *models) {
        self->_assets = [NSMutableArray arrayWithArray:models];
        [self.photoListView scrollRectToVisible:CGRectMake(0, 0, 1, 1) animated:YES];
        [self.photoListView reloadData];
    }];
    
}

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

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *cellIdentifer = @"cell";
    AJPhotoListCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:cellIdentifer forIndexPath:indexPath];
    
    BOOL isSelected = [self.indexPathsForSelectedItems containsObject:self.assets[indexPath.row]];
    [cell bind:self.assets[indexPath.row] selectionFilter:self.selectionFilter isSelected:isSelected];
    
    KWeakSelf
    cell.didClckSelectBut = ^(BOOL isSelect) {
        [weakSelf handlCellSelectFunBy:indexPath];
    };
    
    return cell;
}

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

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    CGFloat wh = (collectionView.bounds.size.width - 20)/3.0;
    return CGSizeMake(wh, wh);
}

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

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

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    PhotoPreviewViewController *vc =[PhotoPreviewViewController new];
    vc.assets = _assets;
    vc.currentIndex = indexPath.row;
    vc.indexPathsForSelectedItems = _indexPathsForSelectedItems;
    vc.maximumNumberOfSelection = _maximumNumberOfSelection;
    vc.minimumNumberOfSelection = _minimumNumberOfSelection;
    vc.availableStorage = self.uploadFileBottomV.availableStorage;
    [self.navigationController pushViewController:vc animated:YES];
    
    KWeakSelf
    vc.changeSelectIndex = ^(NSMutableArray * _Nonnull indexPathsForSelectedItems) {
        [weakSelf refreshDataAndUIFunWith:indexPathsForSelectedItems];
    };
}

#pragma mark 从详情页回来 刷新数据和UI
- (void)refreshDataAndUIFunWith:(NSMutableArray *)indexPathsForSelectedItems
{
    self.indexPathsForSelectedItems = indexPathsForSelectedItems;
    [self refreshAllDataFun];
}

#pragma mark 刷新所有数据
- (void)refreshAllDataFun
{
    [self setDataToBottomViewFun];
    [self.photoListView reloadData];
}

#pragma mark 处理点击选中相关
- (void)handlCellSelectFunBy:(NSIndexPath *)indexPath
{
    
    AJPhotoListCell *cell = (AJPhotoListCell *)[self.photoListView cellForItemAtIndexPath:indexPath];
    TZAssetModel *model = self.assets[indexPath.row];
    
    //超出最大限制
    if (self.indexPathsForSelectedItems.count >= self.maximumNumberOfSelection ) {
        return;
    }
    
    //取消选中
    if ([self.indexPathsForSelectedItems containsObject:model]) {
        [self.indexPathsForSelectedItems removeObject:model];
        model.isSelected = NO;
        [cell isSelected:NO];
    }
    else
    {//选中
        [self didSelectModel:model];
        [cell isSelected:YES];
    }
    
    [self setDataToBottomViewFun];
}

#pragma mark  选中某个cell
- (void)didSelectModel:(TZAssetModel *)model
{//选中
    [self.indexPathsForSelectedItems addObject:model];
    model.isSelected = YES;
    
    if(!model.totalBytes)
    {
        [[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];
             }
            }];

        }

    }
}

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

#pragma mark - getter/setter
- (NSMutableArray *)assets {
    if (!_assets) {
        _assets = [[NSMutableArray alloc] init];
    }
    return _assets;
}

- (NSMutableArray *)indexPathsForSelectedItems {
    if (!_indexPathsForSelectedItems) {
        _indexPathsForSelectedItems = [[NSMutableArray alloc] init];
    }
    return _indexPathsForSelectedItems;
}

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


- (void)getCouldPhoneBaseInfoFun:(NSNotification*)not
{
    couldPhoneBaseInfoModel *baseInfoModel = [not object];
    //HLog(@"%@",baseInfoModel);
    
    if(!baseInfoModel || ![baseInfoModel isKindOfClass:[couldPhoneBaseInfoModel class]]){
        return;
    }
    
    self.uploadFileBottomV.availableStorage = baseInfoModel.data.availableStorage;
    [self setDataToBottomViewFun];
}
@end
