//
//  ICNormalPhotoViewController.m
//  superCleaner
//
//  Created by Mazy on 2020/7/4.
//  Copyright © 2020 Mazy. All rights reserved.
//

#import "ICNormalPhotoViewController.h"
#import "WKSimilarPhotoCell.h"
#import "WKSimilarPhotoHeadView.h"
#import "WKClearPhotoManager.h"
#import "ICNavigationController.h"
#import "ICPhotoViewerController.h"
#import "UIView+DHExtension.h"
#import "ICBasePhotoModel.h"
#import "WKClearPhotoManager.h"

@interface ICNormalPhotoViewController ()<UICollectionViewDelegate, UICollectionViewDataSource>

@property (nonatomic, strong) UICollectionView *collectionView;

@property (nonatomic, strong) UIButton *deleteButton;
@property (nonatomic, strong) NSMutableArray<ICBasePhotoModel *> *itemSource;
@property (nonatomic, strong) UIButton *selectAllBtn;
@property (nonatomic, strong) WKClearPhotoManager *photoMgr;

@end

@implementation ICNormalPhotoViewController

- (WKClearPhotoManager *)photoMgr {
    if (!_photoMgr) {
        _photoMgr = [WKClearPhotoManager shareManager];
    }
    return _photoMgr;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.title = @"屏幕截图";
    
    self.itemSource = [NSMutableArray array];
    
    [self setupUI];
    [self configData];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:false animated:true];
    
    [self.collectionView reloadData];
}

- (void)setupUI {
    
     [self.collectionView reloadData];
    
    UIButton *selectBtn = [[UIButton alloc] init];
    [selectBtn setTitle: ICLocalized(@"ChooseAll") forState:UIControlStateNormal];
    [selectBtn setTitle: ICLocalized(@"CancelAll") forState:UIControlStateSelected];
    [selectBtn setTitleColor:[UIColor colorWithHex:0x030303] forState:UIControlStateNormal];
    selectBtn.titleLabel.font = [UIFont systemFontOfSize:16];
    [selectBtn addTarget:self action:@selector(selectAllOrNotAction:) forControlEvents:UIControlEventTouchUpInside];
    self.selectAllBtn = selectBtn;
    self.selectAllBtn.selected = true;
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:selectBtn];
    
    UIButton *deleteBtn = [[UIButton alloc] init];
    [deleteBtn setBackgroundImage:[UIImage imageNamed:@"global_green_btn_bg"] forState:UIControlStateNormal];
    [deleteBtn setTitle: ICLocalized(@"DeleteScreenshots") forState:UIControlStateNormal]; //@"删除截图"

    [self.view addSubview:deleteBtn];
    [self.view bringSubviewToFront:deleteBtn];
    [deleteBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_equalTo(self.view);
        make.bottom.mas_equalTo(self.view).mas_offset(-40);
        make.height.mas_equalTo(62);
        make.width.mas_equalTo(344);
    }];
    [deleteBtn addTarget:self action:@selector(clickDeleteBtn) forControlEvents:UIControlEventTouchUpInside];
    self.deleteButton.enabled = false;
    self.deleteButton = deleteBtn;
}

- (void)selectAllOrNotAction: (UIButton *)button {
    
    for (ICBasePhotoModel *model in self.itemSource) {
        model.isSelected = !button.isSelected;
    }
    [self.collectionView reloadData];
    self.deleteButton.enabled = !button.isSelected;
    button.selected = !button.isSelected;
}


- (void)clickDeleteBtn {
    
    if ([self.navigationItem.title isEqualToString: ICLocalized(@"Place")]) {
        [MobClick event:@"spot_delete_all"];
    } else {
        [MobClick event:@"screenshot_delete_all_click"];
    }
    
    NSMutableArray *assetArr = [NSMutableArray array];
    NSMutableArray *temDataArr = [NSMutableArray array];
    
    for (ICBasePhotoModel *model in self.itemSource) {
        if (model.isSelected) {
            [assetArr addObject: model.asset];
        } else {
            [temDataArr addObject:model];
        }
    }
    
    if (assetArr.count) {
        [WKClearPhotoManager shareManager].notificationStatus = WKPhotoNotificationStatusClose;
        [WKClearPhotoManager deleteAssets:assetArr
                        completionHandler:^(BOOL success, NSError *error) {
            if (success) {
                [self deleteSuccessWithTemDataArr:temDataArr];
            }
        }];
    }
}

- (void)deleteSuccessWithTemDataArr:(NSMutableArray *)temDataArr {
    self.itemSource = temDataArr;
    [self.collectionView reloadData];
    
    if (_photoType == LocationPhoto){
        NSDictionary *dict = self.photoMgr.locationArray[_currentlocationGroudIndex];
        NSDictionary * newDict = @{[[dict allKeys] firstObject]:temDataArr};
        self.photoMgr.locationArray[_currentlocationGroudIndex] = newDict;
    }else{
        self.photoMgr.snapshotArray = temDataArr;
    }
    [WKClearPhotoManager shareManager].notificationStatus = WKPhotoNotificationStatusNeed;
}

- (void)configData {
    [self.itemSource removeAllObjects];
    
    if (self.similarArr.count <= 0) {
        self.selectAllBtn.hidden = true;
        self.deleteButton.hidden = true;
        [self.view addEmptyDataSet:0 image:[UIImage imageNamed:@"global_empty_set"] title: ICLocalized(@"EmptyScreenshots")]; //@"无截图照片"];
        return;
    }
    self.selectAllBtn.hidden = false;
    self.deleteButton.hidden = false;
    [self.view removeEmptyDataSet:true];
    
    for (ICBasePhotoModel *model in self.similarArr) {
        model.isSelected = true;
        [self.itemSource addObject:model];
    }
//    self.itemSource = [self.similarArr mutableCopy];
    [self.collectionView reloadData];
}

- (void) checkDeleteButtonIsNeedShow {
    NSMutableArray *assetArr = [NSMutableArray array];
    for (ICBasePhotoModel *model in self.itemSource) {
        if (model.isSelected) {
            [assetArr addObject:model.asset];
        }
    }
    self.deleteButton.enabled = assetArr.count > 0;
}

#pragma mark - UICollectionViewDataSource,UICollectionViewDelegate
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return 1;
}

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

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

    [cell bindWithModel:self.itemSource[indexPath.row]];
    
    __weak typeof(self) weakSelf = self;
    cell.refreshViewDataClosre = ^{
        [weakSelf checkDeleteButtonIsNeedShow];
    };
    return cell;
}


- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    ICPhotoViewerController *viewer = [[UIStoryboard storyboardWithName:@"Main" bundle: nil] instantiateViewControllerWithIdentifier:@"ICPhotoViewerController"];
    viewer.itemSource = self.itemSource;
    viewer.currentIndex = indexPath.row;
    ICBasePhotoModel *model = self.itemSource[indexPath.row];
    viewer.photoItem = model;
    viewer.updatePreViewListCallBack = ^(ICBasePhotoModel * item) {
        for (ICBasePhotoModel *model in self.itemSource) {
            if (model.asset == item.asset) {
                model.isSelected = item.isSelected;
            }
        }
        [self checkDeleteButtonIsNeedShow];
        [self.collectionView reloadData];
    };
    viewer.photoType = self.photoType;
    [self.navigationController pushViewController:viewer animated:true];
}

//设置段头view大小
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section {
    return CGSizeMake(0, 0);
}

#pragma mark - 懒加载
- (UICollectionView *)collectionView {
    if (!_collectionView) {
        UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
        CGFloat itemCount = 4;
        CGFloat distance = 8;
        CGFloat width = self.view.frame.size.width;
        CGFloat itemWH = (width - distance * (itemCount + 1)) / itemCount - 1;
        layout.itemSize = CGSizeMake(itemWH, itemWH);
        layout.sectionInset = UIEdgeInsetsMake(distance, distance, distance, distance);
        layout.minimumLineSpacing = distance;
        layout.minimumInteritemSpacing = distance;
        _collectionView = [[UICollectionView alloc] initWithFrame:self.view.bounds
                                             collectionViewLayout:layout];
        _collectionView.dataSource = self;
        _collectionView.delegate = self;
        [_collectionView registerClass:[WKSimilarPhotoCell class]
            forCellWithReuseIdentifier:@"WKSimilarPhotoCell_id"];
        [_collectionView registerClass:[WKSimilarPhotoHeadView class]
            forSupplementaryViewOfKind:UICollectionElementKindSectionHeader
                   withReuseIdentifier:@"WKSimilarPhotoHeadView_id"];
        _collectionView.backgroundColor = [UIColor whiteColor];
        [self.view addSubview:_collectionView];
        
        _collectionView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
        _collectionView.delaysContentTouches = NO;
        if ([UIDevice currentDevice].systemVersion.floatValue >= 11.0) {
            if ([UIScreen mainScreen].bounds.size.height == 812) {
                if (@available(iOS 11.0, *)) {
                    _collectionView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
                } else {
                    // Fallback on earlier versions
                }
                CGFloat h1 = [UIApplication sharedApplication].statusBarFrame.size.height;
                CGFloat h2 = self.navigationController.navigationBar.bounds.size.height;
                _collectionView.contentInset = UIEdgeInsetsMake(h1 + h2, 0, 0, 0);
                _collectionView.scrollIndicatorInsets = UIEdgeInsetsMake(h1 + h2, 0, 0, 0);
            }
        }
        UIEdgeInsets inset = _collectionView.contentInset;
        _collectionView.contentInset = UIEdgeInsetsMake(inset.top, inset.left, 50, inset.right);
        _collectionView.scrollIndicatorInsets = _collectionView.contentInset;
    }
    return _collectionView;
}

@end
