//
//  WKSimilarPhotoViewController.m
//  WuKongClearPhotoDemo
//
//  Created by ZhangJingHao2345 on 2018/3/8.
//  Copyright © 2018年 ZhangJingHao2345. All rights reserved.
//

#import "WKSimilarPhotoViewController.h"
#import "WKSimilarPhotoCell.h"
#import "WKSimilarPhotoHeadView.h"
#import "WKPhotoInfoItem.h"
#import "WKClearPhotoManager.h"
#import "MBProgressHUD.h"
#import "superCleaner-Swift.h"
#import "ICPhotoViewerController.h"
#import "UIView+DHExtension.h"
#import "ICBasePhotoModel.h"

#define random(r, g, b, a) [UIColor colorWithRed:(r)/255.0 green:(g)/255.0 blue:(b)/255.0 alpha:(a)/255.0]
#define randomColor random(arc4random_uniform(256), arc4random_uniform(256), arc4random_uniform(256), 255)

@interface WKSimilarPhotoViewController () <UICollectionViewDelegate, UICollectionViewDataSource>

@property (nonatomic, strong) UICollectionView *collectionView;
@property (nonatomic, strong) NSMutableArray *modelArray;
@property (nonatomic, strong) UIButton *deleteButton;
@property (nonatomic, strong) UIButton *selectAllBtn;
@property (nonatomic, strong) NSMutableArray *itemSource;

@property (nonatomic, strong, readwrite) WKClearPhotoManager *photoMgr;

@end

@implementation WKSimilarPhotoViewController

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

- (void)viewDidLoad {
    [super viewDidLoad];
    
    switch (_photoType) {
        case SimilayNormalPhoto:
            self.navigationItem.title = [NSString stringWithFormat:@"%@ %@", ICLocalized(@"Cleaning"), ICLocalized(@"SimilarMotionPhoto")];// @"清理相似照片";
            break;
            case SimilayLivePhoto:
            self.navigationItem.title = [NSString stringWithFormat:@"%@ %@", ICLocalized(@"Cleaning"), ICLocalized(@"SimilarPhoto")];//@"清理相似动态照片";
            break;
            case SimilayVideoPhoto:
            self.navigationItem.title = [NSString stringWithFormat:@"%@ %@", ICLocalized(@"Cleaning"), ICLocalized(@"SimilarVideo")];//@"清理相似视频";
            break;
            case SimilayContinuousPhoto:
            self.navigationItem.title =[NSString stringWithFormat:@"%@ %@", ICLocalized(@"Cleaning"), ICLocalized(@"SimilarMotionPhoto")];// @"清理相似连拍照片";
            break;
        default:
            break;
    }
    
    self.itemSource = [NSMutableArray array];
    self.modelArray = [NSMutableArray array];
    [self setupUI];
    [self.view bringSubviewToFront:self.deleteButton];
    [self configData];
}

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

- (void)configData {
    [self.itemSource removeAllObjects];
    self.selectAllBtn.hidden = false;
    self.deleteButton.hidden = false;
    if (self.similarArr.count <= 0) {
        /*
         "NoScreenCapture"      = "No Screenshot";
         "NoSimilarPhoto"       = "No Similar Live Photo";
         "NoSimilarVideo"       = "No Similar Video";
         "NoSimilarMotionPhoto" = "No Similar Photo";
         */
        NSString *emptyTitle = @"";
        switch (_photoType) {
            case SimilayNormalPhoto:
                emptyTitle = ICLocalized(@"NoSimilarMotionPhoto"); // @"无相似照片";
                break;
                case SimilayLivePhoto:
                emptyTitle =  ICLocalized(@"NoSimilarPhoto");//@"无相似动态照片";
                break;
                case SimilayVideoPhoto:
                emptyTitle = ICLocalized(@"NoSimilarVideo");//@"无相似视频";
                break;
                case SimilayContinuousPhoto:
                emptyTitle = ICLocalized(@"NoSimilarMotionPhoto");// @"无相似连拍照片";
                break;
            default:
                break;
        }
        self.selectAllBtn.hidden = true;
        self.deleteButton.hidden = true;
        [self.view addEmptyDataSet:0 image:[UIImage imageNamed:@"global_empty_set"] title: emptyTitle];
        return;
    }
    
    [self.view removeEmptyDataSet:true];
    for (NSArray *arr in self.similarArr) {
        NSMutableArray *mutArr = [NSMutableArray arrayWithCapacity:arr.count];
        for (int i = 0; i < arr.count; i++) {
            ICBasePhotoModel *item = arr[i]; //[[WKPhotoInfoItem alloc] initWithDict:infoDict];
            if (i != 0) {
                item.isSelected = YES;
            }
            [mutArr addObject:item];
            [self.modelArray addObject:item];
        }
        
        [self.itemSource addObject:mutArr];
    }
    [self.collectionView reloadData];
}

// 检测删除按钮是否可用
- (void) checkDeleteButtonIsNeedShow {
    NSMutableArray *assetArr = [NSMutableArray array];
    for (NSArray *dict in self.itemSource) {
        for (ICBasePhotoModel *item in dict) {
            if (item.isSelected) {
                [assetArr addObject:item.asset];
            }
        }
    }
    self.deleteButton.enabled = assetArr.count > 0;
}

- (void)setupUI {

    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];
    selectBtn.selected = true;
    self.selectAllBtn = selectBtn;
    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(@"DeleteSimilarPhotos") 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;
    
    [self.collectionView reloadData];
}

- (void)selectAllOrNotAction: (UIButton *)button {
    
    for (NSArray *array in self.itemSource) {
        for (int i = 0; i < array.count; i++) {
            ICBasePhotoModel *item = array[i];
            if (i != 0) {
                item.isSelected = !button.isSelected;
            }
        }
    }
    [self.collectionView reloadData];
    self.deleteButton.enabled = !button.isSelected;
    button.selected = !button.isSelected;
}

- (void)clickDeleteBtn {
    switch (_photoType) {
        case SimilayNormalPhoto:
            [MobClick event:@"similar_photo_delete_all_click"];
            break;
            case SimilayLivePhoto:
            [MobClick event:@"similar_live_photo_delete_click"];
            break;
            case SimilayVideoPhoto:
            [MobClick event:@"similar_photo_delete_all_click"];
        default:
            break;
    }
    NSMutableArray *assetArr = [NSMutableArray array];
    NSMutableArray *temDataArr = [NSMutableArray array];
    
    for (NSArray *arr in self.itemSource) {
        NSMutableArray *mutArr = [NSMutableArray array];
        for (ICBasePhotoModel *item in arr) {
            if (item.isSelected) {
                [assetArr addObject:item.asset];
            } else {
                [mutArr addObject:item];
            }
        }
        
        if (mutArr.count > 1) {
            [temDataArr addObject:mutArr];
        }
    }
    
    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.similarArr = temDataArr;
    self.itemSource = temDataArr;
    switch (self.photoType) {
        case SimilayNormalPhoto:
            self.photoMgr.similarArray = temDataArr;
            break;
            case SimilayLivePhoto:
            self.photoMgr.similarLiveArray = temDataArr;
            break;
        default:
            break;
    }
    [self.collectionView reloadData];
    
    [WKClearPhotoManager tipWithMessage: ICLocalized(@"DeleteSuccess")];
    [WKClearPhotoManager shareManager].notificationStatus = WKPhotoNotificationStatusNeed;
    
}

#pragma mark - UICollectionViewDataSource,UICollectionViewDelegate

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

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    NSArray *array = self.itemSource[section];
    return array.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    
    if (indexPath.row == 0) {
        WKSimilarPhotoCell *cell =
        [collectionView dequeueReusableCellWithReuseIdentifier:@"WKSimilarPhotoCell_id_big"
                                                  forIndexPath:indexPath];
        
        NSArray *array = self.itemSource[indexPath.section];
        [cell bindWithModel:array[indexPath.row]];
        cell.bestIconView.hidden = false;
        __weak typeof(self) weakSelf = self;
        cell.refreshViewDataClosre = ^{
            [weakSelf checkDeleteButtonIsNeedShow];
        };
        return cell;
    }
    WKSimilarPhotoCell *cell =
    [collectionView dequeueReusableCellWithReuseIdentifier:@"WKSimilarPhotoCell_id"
                                              forIndexPath:indexPath];
    
    NSArray *array = self.itemSource[indexPath.section];
    [cell bindWithModel:array[indexPath.row]];
    cell.bestIconView.hidden = true;
    cell.refreshViewDataClosre = ^{
        [self checkDeleteButtonIsNeedShow];
    };
    return cell;
}

- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
{
    if (kind == UICollectionElementKindSectionHeader) {
        WKSimilarPhotoHeadView *headerV =  [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"WKSimilarPhotoHeadView_id" forIndexPath:indexPath];
        NSArray *itemArray = self.itemSource[indexPath.section];
        __weak typeof(self) weakSelf = self;
        headerV.selectAllOrNotClosure = ^(BOOL isSelectAll) {
            for (int i = 0; i < itemArray.count; i++) {
                if (i > 0) {
                    ICBasePhotoModel *item = itemArray[i];
                    item.isSelected = isSelectAll;
                    WKSimilarPhotoCell *cell = (WKSimilarPhotoCell *)[collectionView cellForItemAtIndexPath:[NSIndexPath indexPathForItem:i inSection: indexPath.section]];
                    [cell bindWithModel:item];
                }
            }
            [weakSelf checkDeleteButtonIsNeedShow];
        };
        
        NSMutableArray *selectedArray = [NSMutableArray array];
        for (ICBasePhotoModel *item in itemArray) {
            if (item.isSelected) {
                [selectedArray  addObject:item];
            }
        }
        if (selectedArray.count >= itemArray.count - 1) {
            headerV.selectBtn.selected = true;
        } else {
            headerV.selectBtn.selected = false;
        }
        
        [headerV bindWithCountString:[NSString stringWithFormat:@"%lu%@", (unsigned long)itemArray.count, ICLocalized(@"Photos")]];
        return headerV;
    }
    
    return nil;
}

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

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

#pragma mark - 懒加载

- (UICollectionView *)collectionView {
    if (!_collectionView) {
        FacebookLayout *layout = [[FacebookLayout alloc] init];
        //        layout.delegate = self;
        //        layout.contentPadding = ItemsPadding(horizontal: 15, vertical: 15)
        //        layout.cellsPadding = ItemsPadding(horizontal: 10, vertical: 10)
        //        CGFloat itemCount = 4;
        //        CGFloat distance = 10;
        //        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_big"];
        
        [_collectionView registerClass:[WKSimilarPhotoCell class]
            forCellWithReuseIdentifier:@"WKSimilarPhotoCell_id"];
        
        [_collectionView registerClass:[WKSimilarPhotoHeadView class]
            forSupplementaryViewOfKind:UICollectionElementKindSectionHeader
                   withReuseIdentifier:@"WKSimilarPhotoHeadView_id"];
        
        [self.collectionView registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:@"id"];
        
        _collectionView.backgroundColor = [UIColor whiteColor];
        
        [self.view addSubview:_collectionView];
        
        _collectionView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
        _collectionView.delaysContentTouches = NO;
    }
    return _collectionView;
}

@end
