//
//  ICPhotoManageViewController.m
//  superCleaner
//
//  Created by Mazy on 2020/7/3.
//  Copyright © 2020 Mazy. All rights reserved.
//

#import "ICPhotoManageViewController.h"
#import "ICContactManageViewCell.h"
#import "ICPhotoManageHeaderView.h"
#import "WKClearPhotoManager.h"
#import "MBProgressHUD.h"
#import "WKSimilarPhotoViewController.h"
#import "ICNormalPhotoViewController.h"
#import "ICPhotoLocationViewController.h"

@interface ICPhotoManageViewController ()<UITableViewDataSource, UITableViewDelegate>

@property (nonatomic, strong) UITableView *tableView;

@property (nonatomic, copy) NSMutableArray *dataSource;

@property (nonatomic, strong) WKClearPhotoManager *photoMgr;
@property (nonatomic, strong) ICPhotoManageHeaderView *headerView;
// 所有的图片资源
@property (nonatomic, copy) NSMutableArray *screenshotArray;
@property (nonatomic, copy) NSMutableArray *similarLiveArray;
@property (nonatomic, copy) NSMutableArray *similarPhotoArray;

@end

@implementation ICPhotoManageViewController

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

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.screenshotArray = [NSMutableArray array];
    self.similarLiveArray = [NSMutableArray array];
    self.similarPhotoArray = [NSMutableArray array];
    
    self.tableView = [[UITableView alloc] initWithFrame: self.view.bounds style: UITableViewStylePlain];
    [self.view addSubview:self.tableView];
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.mas_equalTo(self.view);
    }];
    
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.rowHeight = 70;
    self.tableView.tableFooterView = [[UIView alloc] init];
    
    [self.tableView registerNib: [UINib nibWithNibName:@"ICContactManageViewCell" bundle:nil] forCellReuseIdentifier:@"ICContactManageViewCell"];
    
    ICPhotoManageHeaderView *headerView = [ICPhotoManageHeaderView loadFromNib];
    headerView.frame = CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width,  160);
    UIView *headerContainer = [[UIView alloc] init];
    headerContainer.frame = CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width,  160);
    self.headerView = headerView;
    [headerContainer addSubview:headerView];
    self.tableView.tableHeaderView = headerContainer;
    
    __weak typeof(self) weakSelf = self;
    self.headerView.dateSelectFinishedHandle = ^(NSDate * startDate, NSDate * endDate) {
        NSLog(@"%@ -- %@", startDate, endDate);
//        weakSelf.photoMgr.startDate = startDate;
//        weakSelf.photoMgr.endDate   = endDate;
        
        NSMutableArray *temp = [NSMutableArray array];
        for (ICBasePhotoModel *model in weakSelf.photoMgr.snapshotArray) {
            if ([model.asset.creationDate compare:startDate] == NSOrderedDescending && [model.asset.creationDate compare:endDate] == NSOrderedAscending) {
                [temp addObject:model];
            }
        }
        weakSelf.screenshotArray = temp;
        
        NSMutableArray *tempSimilarArray = [NSMutableArray array];
        for (NSArray *arr in weakSelf.photoMgr.similarArray) {
            ICBasePhotoModel *model = arr.firstObject;
            if ([model.asset.creationDate compare:startDate] == NSOrderedDescending && [model.asset.creationDate compare:endDate] == NSOrderedAscending) {
                [tempSimilarArray addObject:arr];
            }
        }
        weakSelf.similarPhotoArray = tempSimilarArray;
        
        NSMutableArray *tempSimilarLiveArray = [NSMutableArray array];
        for (NSArray *arr in weakSelf.photoMgr.similarLiveArray) {
            ICBasePhotoModel *model = arr.firstObject;
            if ([model.asset.creationDate compare:startDate] == NSOrderedDescending && [model.asset.creationDate compare:endDate] == NSOrderedAscending) {
                [tempSimilarLiveArray addObject:arr];
            }
        }
        weakSelf.similarLiveArray = tempSimilarLiveArray;
        
        [weakSelf.tableView reloadData];
        
        
    };
    
    NSDate *lastYear = [[NSCalendar currentCalendar] dateByAddingUnit:NSCalendarUnitYear value:-1 toDate:[NSDate date] options:NSCalendarWrapComponents];
    self.headerView.stratDate = lastYear;
    [self.headerView.startTimeButton setTitle:[self stringWithDate: lastYear] forState:UIControlStateNormal];
    
    self.dataSource = @[ICLocalized(@"ScreenCapture"), ICLocalized(@"Place"), ICLocalized(@"SimilarPhoto"), ICLocalized(@"SimilarVideo"), ICLocalized(@"SimilarMotionPhoto"), ICLocalized(@"SimilarContrnuous")].mutableCopy;
    [self.tableView reloadData];
    [self loadPhotoData: true];
}

- (void)loadLocationAssets {
    
    ICContactManageViewCell *cell = [self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:1 inSection:0]];
    if (self.photoMgr.locationArray.count > 0) {
        cell.countLabel.text = [NSString stringWithFormat:@"%lu", (unsigned long)self.photoMgr.locationArray.count];
        return;
    }
    __weak typeof(self) weakSelf = self;
    [MBProgressHUD showLoading:@"正在查询，请稍后..." toView:self.view];
    [self.photoMgr loadLocationPhotoWithProcess:^(NSInteger current, NSInteger total) {
        NSLog(@"loadLocationPhotoWithProcess %ld", (long)current);
        cell.progressView.strokeStart = ((CGFloat)current / (CGFloat)(total / 4));
        cell.countLabel.text = [NSString stringWithFormat:@"%lu", (unsigned long)weakSelf.photoMgr.locationArray.count];
    } completionHandler:^(BOOL success, NSError *error) {
        [MBProgressHUD hideHUDForView:self.view];
        cell.progressView.strokeStart = 0;
    }];
}

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

    if (self.photoMgr.notificationStatus == WKPhotoNotificationStatusNeed) {
        [self loadPhotoData: true];
        self.photoMgr.notificationStatus = WKPhotoNotificationStatusDefualt;
    }
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    
    self.photoMgr.pauseAction = true;
}

# pragma UITableViewDataSource, UITableViewDelegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.dataSource.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 15;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    return [[UIView alloc] init];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    ICContactManageViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"ICContactManageViewCell" forIndexPath:indexPath];
    cell.subTitleLabel.hidden = true;
    cell.mainTitleLabel.text = self.dataSource[indexPath.row];
    cell.progressView.hidden = false;
    
    switch (indexPath.row) {
        case 0:
            cell.countLabel.text = [NSString stringWithFormat:@"%lu", (unsigned long)self.screenshotArray.count];
            break;
        case 1:
            cell.countLabel.text = [NSString stringWithFormat:@"%lu", (unsigned long)self.photoMgr.locationArray.count];
            break;
        case 2:
        {
            NSInteger similarCount = 0;
            for (NSArray *items in self.similarPhotoArray) {
                similarCount += items.count;
            }
            cell.countLabel.text = [NSString stringWithFormat:@"%lu", (unsigned long)similarCount];
        }
            break;
        case 3:
            cell.countLabel.text = @"0";// [NSString stringWithFormat:@"%lu", (unsigned long)self.photoMgr.snapshotArray.count];
            break;
        case 4:
        {
            NSInteger similarLiveCount = 0;
            for (NSArray *items in self.similarLiveArray) {
                similarLiveCount += items.count;
            }
            
            cell.countLabel.text = [NSString stringWithFormat:@"%lu", (unsigned long)similarLiveCount];
        }
            break;
            
        default:
            cell.countLabel.text = @"0";
            break;
    }
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:true];
    if ([ICUserManager shared].isMember) {
        switch (indexPath.row) {
            case 0: {
                [MobClick event:@"screenshot_click"];
                ICNormalPhotoViewController *vc = [ICNormalPhotoViewController new];
                vc.similarArr = self.screenshotArray;
                vc.photoType = ScreenShotPhoto;
                [self.navigationController pushViewController:vc animated:YES];
            }
                break;
            case 1: {
                [MobClick event:@"spot_click"];
                ICPhotoLocationViewController *vc = [ICPhotoLocationViewController new];
                [self.navigationController pushViewController:vc animated:YES];
            }
                break;
            case 2: {
                WKSimilarPhotoViewController *vc = [WKSimilarPhotoViewController new];
                vc.similarArr = self.similarPhotoArray;
                vc.photoType = SimilayNormalPhoto;
                [self.navigationController pushViewController:vc animated:YES];
            }
                break;
            case 3: {
                [MobClick event:@"cleanphoto_video"];
                WKSimilarPhotoViewController *vc = [WKSimilarPhotoViewController new];
                vc.similarArr = self.photoMgr.videoArray;
                vc.photoType = SimilayVideoPhoto;
                [self.navigationController pushViewController:vc animated:YES];
            }
                break;
            case 4: {
                WKSimilarPhotoViewController *vc = [WKSimilarPhotoViewController new];
                vc.similarArr = self.similarLiveArray;
                vc.photoType = SimilayLivePhoto;
                [self.navigationController pushViewController:vc animated:YES];
            }
                break;
            case 5: {
                WKSimilarPhotoViewController *vc = [WKSimilarPhotoViewController new];
                vc.photoType = SimilayContinuousPhoto;
                [self.navigationController pushViewController:vc animated:YES];
            }
                break;
                
            default:
                break;
        }
    
    } else {
        ICIAPViewController *iapVC = [[UIStoryboard storyboardWithName:@"Main" bundle: nil] instantiateViewControllerWithIdentifier:@"ICIAPViewController"];
        ICNavigationController *navc = [[ICNavigationController alloc] initWithRootViewController:iapVC];
        [self presentViewController:navc animated:true completion:nil];
    }
}


- (void)loadPhotoData: (BOOL)isFirstLoad {
    [self.tableView reloadData];
    
    [MBProgressHUD showLoading:@"正在查询，请稍后..." toView:self.view];
    if (self.photoMgr.currentIndex <= 0) {
            self.photoMgr.pauseAction = false;
            __weak typeof(self) weakSelf = self;
            [self.photoMgr loadPhotoWithProcess:^(NSInteger current, NSInteger total) {

                NSInteger similarLiveCount = 0;
                for (NSArray *items in self.photoMgr.similarLiveArray) {
                    similarLiveCount += items.count;
                }
                NSInteger similarCount = 0;
                for (NSArray *items in self.photoMgr.similarArray) {
                    similarCount += items.count;
                }

                CGFloat f = (similarCount+similarLiveCount+self.photoMgr.snapshotArray.count+self.photoMgr.locationArray.count) != 0 ?  similarCount/(float)(similarCount+similarLiveCount+self.photoMgr.snapshotArray.count+self.photoMgr.locationArray.count) : 0;
                
                CGFloat ff = (similarCount+similarLiveCount+self.photoMgr.snapshotArray.count+self.photoMgr.locationArray.count) != 0 ?  similarLiveCount/(float)(similarCount+similarLiveCount+self.photoMgr.snapshotArray.count+self.photoMgr.locationArray.count) : 0;
                
                ICContactManageViewCell *cell = [weakSelf.tableView cellForRowAtIndexPath:[ NSIndexPath indexPathForRow:0 inSection:0]];
                cell.countLabel.text = [NSString stringWithFormat:@"%lu", (unsigned long)self.photoMgr.snapshotArray.count];

                ICContactManageViewCell *cell1 = [weakSelf.tableView cellForRowAtIndexPath:[ NSIndexPath indexPathForRow:4 inSection:0]];
                cell1.countLabel.text = [NSString stringWithFormat:@"%lu", (unsigned long)similarLiveCount];
                cell1.progressView.strokeStart = ff;
                
                ICContactManageViewCell *cell2 = [weakSelf.tableView cellForRowAtIndexPath:[ NSIndexPath indexPathForRow:2 inSection:0]];
                cell2.countLabel.text = [NSString stringWithFormat:@"%lu", (unsigned long)similarCount];
                cell2.progressView.strokeStart = f;
                
                ICContactManageViewCell *cell3 = [weakSelf.tableView cellForRowAtIndexPath:[ NSIndexPath indexPathForRow:1 inSection:0]];
                cell3.countLabel.text = [NSString stringWithFormat:@"%lu", (unsigned long)self.photoMgr.locationArray.count];
                
            } completionHandler:^(BOOL success, NSError *error) {
                //        [weakSelf configData];
                PHAsset *asset = self.photoMgr.fetchResult.lastObject;
                if (asset) {
                    [self.headerView.startTimeButton setTitle:[self stringWithDate: asset.creationDate] forState:UIControlStateNormal];
                }
        //        self.assetArr = self.photoMgr.assetArr;
                ICContactManageViewCell *cell = [weakSelf.tableView cellForRowAtIndexPath:[ NSIndexPath indexPathForRow:0 inSection:0]];
                ICContactManageViewCell *cell1 = [weakSelf.tableView cellForRowAtIndexPath:[ NSIndexPath indexPathForRow:2 inSection:0]];
                ICContactManageViewCell *cell2 = [weakSelf.tableView cellForRowAtIndexPath:[ NSIndexPath indexPathForRow:4 inSection:0]];
                cell.progressView.strokeStart = 1;
                cell1.progressView.strokeStart = 1;
                cell2.progressView.strokeStart = 1;
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.25 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    cell.progressView.strokeStart = 0;
                    cell1.progressView.strokeStart = 0;
                    cell2.progressView.strokeStart = 0;
                });
                
                self.screenshotArray = self.photoMgr.snapshotArray;
                self.similarPhotoArray = self.photoMgr.similarArray;
                self.similarLiveArray = self.photoMgr.similarLiveArray;
                [MBProgressHUD hideHUDForView:self.view];
                [self loadLocationAssets];
                [self.tableView reloadData];
            }];
    } else if (self.photoMgr.currentIndex >= self.photoMgr.fetchResult.count-3) {
        
        PHAsset *asset = self.photoMgr.fetchResult.lastObject;
        if (asset) {
            [self.headerView.startTimeButton setTitle:[self stringWithDate: asset.creationDate] forState:UIControlStateNormal];
        }

        if (self.photoMgr.similarLiveArray.count) {
            
        }
        if (self.photoMgr.similarArray.count) {
            
        }
        
        ICContactManageViewCell *cell = [self.tableView cellForRowAtIndexPath:[ NSIndexPath indexPathForRow:0 inSection:0]];
        cell.countLabel.text = [NSString stringWithFormat:@"%lu", (unsigned long)self.photoMgr.snapshotArray.count];

        NSInteger similarLiveCount = 0;
        for (NSArray *items in self.photoMgr.similarLiveArray) {
            similarLiveCount += items.count;
        }
        ICContactManageViewCell *cell1 = [self.tableView cellForRowAtIndexPath:[ NSIndexPath indexPathForRow:4 inSection:0]];
        cell1.countLabel.text = [NSString stringWithFormat:@"%lu", (unsigned long)similarLiveCount];

        NSInteger similarCount = 0;
        for (NSArray *items in self.photoMgr.similarArray) {
            similarCount += items.count;
        }
        ICContactManageViewCell *cell2 = [self.tableView cellForRowAtIndexPath:[ NSIndexPath indexPathForRow:2 inSection:0]];
        cell2.countLabel.text = [NSString stringWithFormat:@"%lu", (unsigned long)similarCount];

        ICContactManageViewCell *cell3 = [self.tableView cellForRowAtIndexPath:[ NSIndexPath indexPathForRow:1 inSection:0]];
        cell3.countLabel.text = [NSString stringWithFormat:@"%lu", (unsigned long)self.photoMgr.locationArray.count];
        self.screenshotArray = self.photoMgr.snapshotArray;
        self.similarPhotoArray = self.photoMgr.similarArray;
        self.similarLiveArray = self.photoMgr.similarLiveArray;
        [MBProgressHUD hideHUDForView:self.view];
        [self loadLocationAssets];
        [self.tableView reloadData];
        return;
    } else {
        self.photoMgr.pauseAction = true;
        __weak typeof(self) weakSelf = self;
        [self.photoMgr loadPhotoWithProcess:^(NSInteger current, NSInteger total) {

            PHAsset *asset = self.photoMgr.fetchResult.lastObject;
            if (asset) {
                [self.headerView.startTimeButton setTitle:[self stringWithDate: asset.creationDate] forState:UIControlStateNormal];
            }
            
            NSInteger similarLiveCount = 0;
            for (NSArray *items in self.photoMgr.similarLiveArray) {
                similarLiveCount += items.count;
            }
            NSInteger similarCount = 0;
            for (NSArray *items in self.photoMgr.similarArray) {
                similarCount += items.count;
            }
            
            CGFloat f = (similarCount+similarLiveCount+self.photoMgr.snapshotArray.count+self.photoMgr.locationArray.count) != 0 ?  similarCount/(float)(similarCount+similarLiveCount+self.photoMgr.snapshotArray.count+self.photoMgr.locationArray.count) : 0;
            
            CGFloat ff = (similarCount+similarLiveCount+self.photoMgr.snapshotArray.count+self.photoMgr.locationArray.count) != 0 ?  similarLiveCount/(float)(similarCount+similarLiveCount+self.photoMgr.snapshotArray.count+self.photoMgr.locationArray.count) : 0;
            
            ICContactManageViewCell *cell = [weakSelf.tableView cellForRowAtIndexPath:[ NSIndexPath indexPathForRow:0 inSection:0]];
            cell.countLabel.text = [NSString stringWithFormat:@"%lu", (unsigned long)self.photoMgr.snapshotArray.count];

            ICContactManageViewCell *cell1 = [weakSelf.tableView cellForRowAtIndexPath:[ NSIndexPath indexPathForRow:4 inSection:0]];
            cell1.countLabel.text = [NSString stringWithFormat:@"%lu", (unsigned long)similarLiveCount];
            cell1.progressView.strokeStart = ff;

            ICContactManageViewCell *cell2 = [weakSelf.tableView cellForRowAtIndexPath:[ NSIndexPath indexPathForRow:2 inSection:0]];
            cell2.countLabel.text = [NSString stringWithFormat:@"%lu", (unsigned long)similarCount];
            cell2.progressView.strokeStart = f;

            ICContactManageViewCell *cell3 = [weakSelf.tableView cellForRowAtIndexPath:[ NSIndexPath indexPathForRow:1 inSection:0]];
            cell3.countLabel.text = [NSString stringWithFormat:@"%lu", (unsigned long)self.photoMgr.locationArray.count];

        } completionHandler:^(BOOL success, NSError *error) {

            PHAsset *asset = self.photoMgr.fetchResult.lastObject;
            if (asset) {
                [self.headerView.startTimeButton setTitle:[self stringWithDate: asset.creationDate] forState:UIControlStateNormal];
            }

            //        self.assetArr = self.photoMgr.assetArr;
            ICContactManageViewCell *cell = [weakSelf.tableView cellForRowAtIndexPath:[ NSIndexPath indexPathForRow:0 inSection:0]];
            ICContactManageViewCell *cell1 = [weakSelf.tableView cellForRowAtIndexPath:[ NSIndexPath indexPathForRow:2 inSection:0]];
            ICContactManageViewCell *cell2 = [weakSelf.tableView cellForRowAtIndexPath:[ NSIndexPath indexPathForRow:4 inSection:0]];
            cell.progressView.strokeStart = 1;
            cell1.progressView.strokeStart = 1;
            cell2.progressView.strokeStart = 1;
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.25 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                cell.progressView.strokeStart = 0;
                cell1.progressView.strokeStart = 0;
                cell2.progressView.strokeStart = 0;
            });

            self.screenshotArray = self.photoMgr.snapshotArray;
            self.similarPhotoArray = self.photoMgr.similarArray;
            self.similarLiveArray = self.photoMgr.similarLiveArray;
            [MBProgressHUD hideHUDForView:self.view];
            [self loadLocationAssets];
            [self.tableView reloadData];
        }];
    }
}

// NSDate转NSString
- (NSString *)stringWithDate:(NSDate *)date {
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    
    NSString *language = [[NSLocale preferredLanguages] firstObject];
    if ([language containsString: @"zh"]) {
        [dateFormatter setDateFormat: @"MM月, yyyy"];
    } else {
        [dateFormatter setDateFormat: @"MM, yyyy"];
    }
    return [dateFormatter stringFromDate:date];
}

@end
