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

#import "WKClearPhotoViewController.h"
#import "WKClearPhotoManager.h"
#import "MBProgressHUD.h"
#import "WKSimilarPhotoViewController.h"
#import "LXCircle.h"
#import "ICNormalPhotoViewController.h"
#import "WKPhotoInfoItem.h"
#import "ICBasePhotoModel.h"

@interface WKClearPhotoViewController () <WKClearPhotoManagerDelegate>

//@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSArray *dataArr;
@property (nonatomic, strong) WKClearPhotoManager *photoMgr;
@property (nonatomic, weak) MBProgressHUD *hud;

@property (weak, nonatomic) IBOutlet UIView *screenshotContentView;
@property (weak, nonatomic) IBOutlet UIView *livePhotoContentView;
@property (weak, nonatomic) IBOutlet UIView *similarPhotoContentView;
@property (weak, nonatomic) IBOutlet UIView *similarVideoContentView;

@property (weak, nonatomic) IBOutlet UILabel *stepTipLabel;
@property (weak, nonatomic) IBOutlet UILabel *processTipLabel;

@property (weak, nonatomic) IBOutlet UIView *sepratorLineView;
@property (weak, nonatomic) IBOutlet UIButton *pauseButton;

@property (weak, nonatomic) IBOutlet UILabel *snapshotCountLabel;
@property (weak, nonatomic) IBOutlet UILabel *livePhotoCountLabel;
@property (weak, nonatomic) IBOutlet UILabel *similarPhotoCountLabel;
@property (weak, nonatomic) IBOutlet UILabel *similarVideoCountLabel;

@property (weak, nonatomic) IBOutlet UIButton *clearAllButton;

@property (weak, nonatomic) IBOutlet UIButton *snapshotSelectBtn;
@property (weak, nonatomic) IBOutlet UIButton *similarLiveSelectBtn;
@property (weak, nonatomic) IBOutlet UIButton *similarPhotoSelectBtn;
@property (weak, nonatomic) IBOutlet UIButton *similarVideoSelectBtn;

@property (nonatomic, strong) LXCircle *progressView;

@property (weak, nonatomic) IBOutlet UIView * topView;
@property (weak, nonatomic) IBOutlet UIView * processBgView;

@property (weak, nonatomic) IBOutlet NSLayoutConstraint * topHeight;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint * cellHeight;

@end

@implementation WKClearPhotoViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self setupUI];
    
    [MobClick event:@"ai_cleanup"];
        
    self.photoMgr.delegate = self;
    
    [self.clearAllButton addTarget:self action:@selector(clearAllPhotoAction:) forControlEvents:UIControlEventTouchUpInside];
    
    [self loadPhotoData];
}

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

- (void)setupUI{
    [super setupUI];
    
    UIImage * titleImage = [UIImage imageNamed:ICLocalized(@"home_nav_center_title")];
    UIImageView * titleImv = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, titleImage.size.width, titleImage.size.height)];
    titleImv.image = titleImage;
    self.navigationItem.titleView = titleImv;
   
    _cellHeight.constant = KScaleWidth(167);
    
    [self.view layoutIfNeeded];
    [self.view layoutSubviews];
    
    self.progressView = [[LXCircle alloc] initWithFrame:self.processBgView.bounds lineWidth: 1];
    [self.processBgView addSubview: self.progressView];
    
    _snapshotSelectBtn.hidden = YES;
    _similarLiveSelectBtn.hidden = YES;
    _similarPhotoSelectBtn.hidden = YES;
    _similarVideoSelectBtn.hidden = YES;
    
    _screenshotContentView.backgroundColor = kMassColorAlpha(0.15);
    _livePhotoContentView.backgroundColor = kMassColorAlpha(0.15);
    _similarPhotoContentView.backgroundColor = kMassColorAlpha(0.15);
    _similarVideoContentView.backgroundColor = kMassColorAlpha(0.15);
    
    _screenshotContentView.tag = 0x8c+1;
    _livePhotoContentView.tag = 0x8c+3;
    _similarPhotoContentView.tag = 0x8c;
    _similarVideoContentView.tag = 0x8c+2;
    
    UITapGestureRecognizer * tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(viewTapGes:)];
    UITapGestureRecognizer * tap1 = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(viewTapGes:)];
    UITapGestureRecognizer * tap2 = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(viewTapGes:)];
    UITapGestureRecognizer * tap3 = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(viewTapGes:)];
    [_screenshotContentView addGestureRecognizer:tap];
    [_livePhotoContentView addGestureRecognizer:tap1];
    [_similarPhotoContentView addGestureRecognizer:tap2];
    [_similarVideoContentView addGestureRecognizer:tap3];
}

- (void)viewTapGes:(UITapGestureRecognizer *)ges{
    switch (ges.view.tag-0x8c) {
        case 0:
            [self similarPhotoDetailAction];
            break;
        case 1:
            [self screenshotDetailAction];
            break;
        case 2:
            
            break;
        case 3:
            [self livePhotoDetailAction];
            break;
            
        default:
            break;
    }
}

- (void)updateUI{
    
    self.navigationItem.titleView = nil;
    self.navigationItem.title = @"要清理的文件";
    
    UIButton * settingBtn = [[UIButton alloc] initWithFrame:CGRectMake(0, KScreenWidth-44, 44, 44)];
    [settingBtn setTitle:@"取消" forState:(UIControlStateNormal)];
    [settingBtn setTitleColor:kMassColor forState:UIControlStateNormal];
    [settingBtn addTarget:self action:@selector(dismissAction)    forControlEvents:(UIControlEventTouchUpInside)];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:settingBtn];
    
    _snapshotSelectBtn.hidden = NO;
    _similarLiveSelectBtn.hidden = NO;
    _similarPhotoSelectBtn.hidden = NO;
    _similarVideoSelectBtn.hidden = NO;

    [self.view layoutIfNeeded];
    [self.view layoutSubviews];
}

- (IBAction)dismissAction {
    if (self.photoMgr.fetchResult.count <= 0) {
        [self dismissViewControllerAnimated:false completion:nil];
        return;
    }
    UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:ICLocalized(@"SureExit") message:ICLocalized(@"CurrentLost") preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *cancel = [UIAlertAction actionWithTitle:ICLocalized(@"Cancel") style:UIAlertActionStyleCancel handler:nil];
    UIAlertAction *commit = [UIAlertAction actionWithTitle:ICLocalized(@"Sure") style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self dismissViewControllerAnimated:false completion:nil];
    }];
    [alertVC addAction:cancel];
    [alertVC addAction:commit];
    [self presentViewController:alertVC animated:true completion:nil];
}

- (void)sureToDismissAction {
     [self dismissViewControllerAnimated:false completion:nil];
}

- (IBAction)pauseAction:(UIButton *)sender {
    
    self.photoMgr.pauseAction = true;
    [self updateViewsWithAllCompleted];
}

// 清除动作
- (void)clearAllPhotoAction:(UIButton *)sender {
    
    [MobClick event:@"clean_all_button"];
    if ([ICUserManager shared].isMember) {
        NSMutableArray<PHAsset *> *deleteItems = [NSMutableArray array];
        CGFloat size = 0;
        if (self.snapshotSelectBtn.isSelected) {
            for (ICBasePhotoModel *item in self.photoMgr.snapshotArray) {
                [deleteItems addObject:item.asset];
                size += item.imageSize;
            }
        }
        
        if (self.similarLiveSelectBtn.isSelected) {
            for (NSArray *arr in self.photoMgr.similarLiveArray) {
                for (int i = 0; i < arr.count; i++) {
                    ICBasePhotoModel *item = arr[i];
                    if (i != 0) {
                        [deleteItems addObject:item.asset];
                        size += item.imageSize;
                    }
                }
            }
        }
        
        if (self.similarPhotoSelectBtn.isSelected) {
            for (NSArray *arr in self.photoMgr.similarArray) {
                for (int i = 0; i < arr.count; i++) {
                    ICBasePhotoModel *item = arr[i];
                    if (i != 0) {
                        [deleteItems addObject:item.asset];
                        size += item.imageSize;
                    }
                }
            }
        }
        
        if (deleteItems.count) {
            
            self.screenshotContentView.hidden = true;
            self.livePhotoContentView.hidden = true;
            self.similarPhotoContentView.hidden = true;
            self.similarVideoContentView.hidden = true;
            self.pauseButton.hidden = true;
            self.clearAllButton.hidden = true;
            self.sepratorLineView.hidden = true;
            self.progressView.hidden = true;
            self.clearAllButton.hidden = true;
            self.stepTipLabel.text = ICLocalized(@"CleaningCameraFilm"); // @"正在清理相机胶卷…";
            self.processTipLabel.hidden = true;
            self.stepTipLabel.hidden = false;
            
            [WKClearPhotoManager shareManager].notificationStatus = WKPhotoNotificationStatusClose;
            [WKClearPhotoManager deleteAssets: deleteItems
                            completionHandler:^(BOOL success, NSError *error) {
                
                
                if (success) {
                    [self deleteSuccessWithTemDataArr:deleteItems.count freeSize:size];
                } else {
                    
                    self.screenshotContentView.hidden = false;
                    self.livePhotoContentView.hidden = false;
                    self.similarPhotoContentView.hidden = false;
                    self.similarVideoContentView.hidden = true;
                    self.pauseButton.hidden = true;
                    self.clearAllButton.hidden = false;
                    self.stepTipLabel.hidden = true;
                    self.processTipLabel.hidden = true;
                    self.sepratorLineView.hidden = true;
                }
            }];
        } else {
            [MBProgressHUD showError: ICLocalized(@"NoPhotosCleanup")];//@"无照片可清理"];
        }
    } else {
        ICIAPViewController *iapVC = [[UIStoryboard storyboardWithName:@"Main" bundle: nil] instantiateViewControllerWithIdentifier:@"ICIAPViewController"];
        ICNavigationController *navc = [[ICNavigationController alloc] initWithRootViewController:iapVC];
        [self presentViewController:navc animated:true completion:nil];
    }
    
}

- (void)deleteSuccessWithTemDataArr: (NSInteger)count freeSize: (CGFloat)size {
    self.dataArr = nil;
    
    [WKClearPhotoManager tipWithMessage:ICLocalized(@"DeleteSuccess")];
    
    self.pauseButton.hidden = true;
    self.sepratorLineView.hidden = true;
    self.progressView.hidden = true;
    self.clearAllButton.hidden = false;
    [self.clearAllButton removeTarget:nil action:NULL forControlEvents:UIControlEventAllEvents];
    [self.clearAllButton setTitle:ICLocalized(@"ItsCool") forState: UIControlStateNormal];
    self.stepTipLabel.hidden = false;
    self.processTipLabel.hidden = false;
    self.stepTipLabel.text = [NSString stringWithFormat:@"%.2fMB%@", size / 1024 / 1024, ICLocalized(@"Cleared")];
    self.processTipLabel.text = [NSString stringWithFormat:@"%ld%@", (long)count, ICLocalized(@"FilesHaveBeenDeleted")];//个文件已被删除
    
    [self.clearAllButton addTarget:self action:@selector(sureToDismissAction) forControlEvents:UIControlEventTouchUpInside];
    
    [WKClearPhotoManager shareManager].notificationStatus = WKPhotoNotificationStatusNeed;
}

- (IBAction)screenshotDetailAction {
        [MobClick event:@"screenshot_click"];
    if ([ICUserManager shared].isMember) {
        ICNormalPhotoViewController *vc = [ICNormalPhotoViewController new];
        vc.similarArr = self.photoMgr.snapshotArray;
        vc.photoType = ScreenShotPhoto;
        vc.navigationItem.title = ICLocalized(@"ScreenCapture"); //@"屏幕截图";
        [self.navigationController pushViewController:vc animated:YES];
    } else {
        ICIAPViewController *iapVC = [[UIStoryboard storyboardWithName:@"Main" bundle: nil] instantiateViewControllerWithIdentifier:@"ICIAPViewController"];
        ICNavigationController *navc = [[ICNavigationController alloc] initWithRootViewController:iapVC];
        [self presentViewController:navc animated:true completion:nil];
    }
}

- (IBAction)livePhotoDetailAction {
    [MobClick event:@"similar_live_photo_click"];
    if ([ICUserManager shared].isMember) {
        WKSimilarPhotoViewController *vc = [WKSimilarPhotoViewController new];
        vc.similarArr = self.photoMgr.similarLiveArray;
        vc.navigationItem.title = ICLocalized(@"SimilarPhoto"); //@"类似动态照片";
        vc.photoType = SimilayLivePhoto;
        [self.navigationController pushViewController:vc animated:YES];
    } else {
        ICIAPViewController *iapVC = [[UIStoryboard storyboardWithName:@"Main" bundle: nil] instantiateViewControllerWithIdentifier:@"ICIAPViewController"];
        ICNavigationController *navc = [[ICNavigationController alloc] initWithRootViewController:iapVC];
        [self presentViewController:navc animated:true completion:nil];
    }
}

- (IBAction)similarPhotoDetailAction {
    [MobClick event:@"similar_photo_click"];
    if ([ICUserManager shared].isMember) {
        WKSimilarPhotoViewController *vc = [WKSimilarPhotoViewController new];
        vc.similarArr = self.photoMgr.similarArray;
        vc.navigationItem.title = ICLocalized(@"SimilarMotionPhoto"); //@"相似照片";
        vc.photoType = SimilayNormalPhoto;
        [self.navigationController pushViewController:vc animated:YES];
    } else {
        ICIAPViewController *iapVC = [[UIStoryboard storyboardWithName:@"Main" bundle: nil] instantiateViewControllerWithIdentifier:@"ICIAPViewController"];
        ICNavigationController *navc = [[ICNavigationController alloc] initWithRootViewController:iapVC];
        [self presentViewController:navc animated:true completion:nil];
    }
}

- (IBAction)photoClearTypeSelectAction:(UIButton *)sender {
    sender.selected = !sender.isSelected;
    if (!self.snapshotSelectBtn.isSelected && !self.similarLiveSelectBtn.isSelected && !self.similarPhotoSelectBtn.isSelected) {
        self.clearAllButton.enabled = false;
    } else {
        self.clearAllButton.enabled = true;
    }
}

- (void)loadPhotoData {
    
    self.photoMgr.currentIndex = 0;
    self.photoMgr.pauseAction = false;
    __weak typeof(self) weakSelf = self;
    [self.photoMgr loadPhotoWithProcess:^(NSInteger current, NSInteger total) {
//        hud.progress = (CGFloat)current / total;
        weakSelf.progressView.progress = (CGFloat)current / total;
        weakSelf.progressLabel.text = [NSString stringWithFormat:@"%.2f%%", ((CGFloat)current / total)*100];
        
        weakSelf.stepTipLabel.text = [NSString stringWithFormat:@"%@: 1/4", ICLocalized(@"Step")];
        weakSelf.processTipLabel.text = ICLocalized(@"LookingScreenShots"); //@"正在寻找屏幕截图…";
        
        if (current > self.photoMgr.snapshotArray.count) {
            weakSelf.screenshotContentView.transform = CGAffineTransformIdentity;
            weakSelf.stepTipLabel.text = [NSString stringWithFormat:@"%@: 2/4", ICLocalized(@"Step")];
            weakSelf.processTipLabel.text = ICLocalized(@"LookingSimilarPhotos");//@"正在寻找相似照片…";
        }

        if (self.photoMgr.similarArray.count > 0) {
            [UIView animateWithDuration:0.25 animations:^{
                weakSelf.similarPhotoContentView.transform = CGAffineTransformIdentity;
            }];
            if (self.photoMgr.similarLiveArray.count > 0) {
                [UIView animateWithDuration:0.25 animations:^{
                    weakSelf.livePhotoContentView.transform = CGAffineTransformIdentity;
                }];
                weakSelf.stepTipLabel.text = [NSString stringWithFormat:@"%@: 3/4", ICLocalized(@"Step")];
                weakSelf.processTipLabel.text = ICLocalized(@"LookingLivePhotos"); // @"正在寻找类似动态照片…";
            }
        }
        
        if ((CGFloat)current / total >= 0.9 && (CGFloat)current / total <= 1) {
            weakSelf.stepTipLabel.text = [NSString stringWithFormat:@"%@: 4/4", ICLocalized(@"Step")];
            weakSelf.processTipLabel.text = ICLocalized(@"LookingSimilarVideos"); //@"正在寻找相似视频…";
        }

        [weakSelf configData];
    } completionHandler:^(BOOL success, NSError *error) {
        
        weakSelf.progressView.progress = 1.f;
        weakSelf.progressLabel.text = @"100.00%";
        
        [weakSelf configData];
        [weakSelf updateUI];

        if (self.photoMgr.fetchResult.count <= 0) {
            [self.clearAllButton setTitle:ICLocalized(@"ContinueSearching") forState:UIControlStateNormal];
            self.stepTipLabel.text = ICLocalized(@"NoFilesRemove"); //@"无文件可删除";
            self.processTipLabel.text = ICLocalized(@"ContinueSearching"); //@"什么也没找到，继续搜索。";
            return;
        }
        
        [self updateViewsWithAllCompleted];
    }];
}

- (void)updateViewsWithAllCompleted {
    
    _topHeight.constant = 0;
    _cellHeight.constant = KScaleWidth(187);
    self.clearAllButton.hidden = false;
    self.clearAllButton.alpha = 0;
    
    [UIView animateWithDuration:0.33 animations:^{
        self.topView.alpha = 0;
        self.clearAllButton.alpha = 1;
        self.clearAllButton.hidden = false;
        [self.view layoutIfNeeded];
    } completion:^(BOOL finished) {
        
    }];
}

- (void)configData {
    
    self.snapshotCountLabel.text = [NSString stringWithFormat:@"%lu%@",
                                    (unsigned long)self.photoMgr.snapshotArray.count, ICLocalized(@"Photos")];
    
    NSInteger similarLiveCount = 0;
    for (NSArray *items in self.photoMgr.similarLiveArray) {
        similarLiveCount += items.count;
    }
    self.livePhotoCountLabel.text = [NSString stringWithFormat:@"%lu%@",
                                     (unsigned long)similarLiveCount, ICLocalized(@"Photos")];
    
    NSInteger similarCount = 0;
    for (NSArray *dict in self.photoMgr.similarArray) {
        similarCount += dict.count;
    }
    self.similarPhotoCountLabel.text = [NSString stringWithFormat:@"%ld%@",
                                        (unsigned long)similarCount, ICLocalized(@"Photos")];
    
    _snapshotSelectBtn.selected = self.photoMgr.snapshotArray.count != 0;
    _similarLiveSelectBtn.selected = self.photoMgr.similarLiveArray.count != 0;
    _similarPhotoSelectBtn.selected = self.photoMgr.similarArray.count != 0;
}

#pragma mark - WKClearPhotoManagerDelegate

// 相册变动代理方法
- (void)clearPhotoLibraryDidChange {
//    [self loadPhotoData];
}

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

@end
