//
//  ICHomeViewController.m
//  superCleaner
//
//  Created by Mazy on 2020/7/2.
//  Copyright © 2020 Mazy. All rights reserved.
//

#import "ICHomeViewController.h"
#import "WKClearPhotoViewController.h"
#import "ICNavigationController.h"
#import "UIView+RadarAnimation.h"
#import "ICSettingTableViewController.h"
#import "ICIAPViewController.h"
#import "ICUserManager.h"
#import <Photos/Photos.h>
#import "ICDiskKit.h"
#import "SCHomeCell.h"
#import "ICCleanDustViewController.h"
#import "ICDbTestViewController.h"
#import "ICNetworkSpeedViewController.h"
#import "ICBatteryCareViewController.h"
#import "ICPhotoManageViewController.h"
#import "ICCalendarManageController.h"
#import "StatisticsViewController.h"
#import "SCHomeHeaderView.h"


@interface ICHomeViewController ()<UICollectionViewDelegate,UICollectionViewDataSource>

@property (weak, nonatomic) IBOutlet UICollectionView * collectionView;
@property (strong, nonatomic) SCHomeHeaderView * headerView;
@property (strong, nonatomic) NSArray * dataSource;

@end

@implementation ICHomeViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    _dataSource = @[@{@"image":@"home_cell_0", @"title":@"照片和视频", @"details":@"清除相似照片与视频"},
                   @{@"image":@"home_cell_2", @"title":@"日历和提醒事项", @"details":@"清理过期提醒事项"},
                   @{@"image":@"home_cell_3", @"title":@"手机清灰", @"details":@"除尘·修复听筒音量"},
                   @{@"image":@"home_cell_4", @"title":@"网速检测", @"details":@"一键测试你的网络速度"},
                   @{@"image":@"home_cell_5", @"title":@"分贝检测", @"details":@"专业的噪音检测仪"},
                   @{@"image":@"home_cell_6", @"title":@"电池寿命", @"details":@"延长iPhone电池寿命"},
                    /*@{@"image":@"home_cell_7", @"title":@"相册统计", @"details":@"种类占比"}*/];
    
    [self setupUI];

    [[ICUserManager shared] loginAndGetUserInfo:^(ZTUserInfoModel * _Nonnull model) {
        [[ICUserManager shared] getServiceInfo];
        
        if (!model.isMember) {
            ICIAPViewController *iapVC = [[UIStoryboard storyboardWithName:@"Main" bundle: nil] instantiateViewControllerWithIdentifier:@"ICIAPViewController"];
            ICNavigationController *navc = [[ICNavigationController alloc] initWithRootViewController:iapVC];
            [self presentViewController:navc animated:true completion:nil];
        }
        
    } failure:^{
        
    }];
    
    NSMutableDictionary *dict = @{@"event": @"guazinovel", @"action": @"tab_imp", @"value": @""}.mutableCopy;
    [[ZTNetworkTools shared] postWithLogCollection:logCollection parameters:dict success:^(id  _Nullable __autoreleasing * _Nullable response) {
    } failure:^(NSError * _Nonnull error) {
    }];
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    [self.headerView.smartClearButton addRadarAnimation];
}

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

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [self.headerView.smartClearButton removeRadarAnimation];
}

- (void)setupUI{
    [super setupUI];
    
    self.navigationItem.title = ICLocalized(@"Back");
       
    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;
   
    UIButton * settingBtn = [[UIButton alloc] initWithFrame:CGRectMake(0, KScreenWidth-44, 44, 44)];
    [settingBtn setImage:[UIImage imageNamed:ICLocalized(@"home_nav_right_setting")] forState:(UIControlStateNormal)];
    [settingBtn addTarget:self action:@selector(showSettingAction:)    forControlEvents:(UIControlEventTouchUpInside)];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:settingBtn];
   
    [self.view layoutIfNeeded];
    [self.view layoutSubviews];
    
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    layout.itemSize = CGSizeMake((KScreenWidth-20)/2, KScaleWidth(78));
    layout.minimumLineSpacing = 0;
    layout.minimumInteritemSpacing = 0;
    layout.sectionInset = UIEdgeInsetsMake(0, 0, 0, 0);
    _collectionView.collectionViewLayout = layout;
    _collectionView.delegate = self;
    _collectionView.dataSource = self;
    _collectionView.showsVerticalScrollIndicator = NO;
//    [_collectionView registerNib:[UINib nibWithNibName:@"ZJChooseIconCell" bundle:nil] forCellWithReuseIdentifier:@"cell"];
    [_collectionView registerNib:[UINib nibWithNibName:@"SCHomeHeaderView" bundle:nil] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"SCHomeHeaderView"];
}

//设置一个函数 便于嵌套使用
-(void)rotateAction{
    [UIView animateWithDuration: 2 delay:0 options:UIViewAnimationOptionCurveLinear animations:^{
        self.headerView.cycleImageView.transform = CGAffineTransformRotate(self.headerView.cycleImageView.transform, M_PI);
    } completion:^(BOOL finished) {
        [self rotateAction];
    }];
}

- (IBAction)showSettingAction:(UIButton *)sender {
    ICSettingTableViewController *settingVC = [[UIStoryboard storyboardWithName:@"Main" bundle: nil] instantiateViewControllerWithIdentifier:@"ICSettingTableViewController"];
    [self.navigationController pushViewController:settingVC animated:true];
}


- (void)getDivceSize{
    
    NSDictionary *fattributes = [[NSFileManager defaultManager] attributesOfFileSystemForPath:NSHomeDirectory() error:nil];
    
    NSNumber *freeber = [fattributes objectForKey:NSFileSystemFreeSize];
    NSNumber *maxber = [fattributes objectForKey:NSFileSystemSize];
    
    long long freespace = [freeber longLongValue];
    long long maxspace = [maxber longLongValue];
    
    CGFloat totalMem = (double)maxspace/1000/1000/1000;
    CGFloat usedMem = totalMem - (CGFloat)freespace/1000/1000/1000;
    
    NSLog(@"%.1f/%.0f", usedMem, totalMem);
    NSLog(@"%.2f", usedMem/totalMem);

    self.headerView.usedSpaceScaleLabel.text = [NSString stringWithFormat:@"%@ %.0f%%",ICLocalized(@"Used"), [[ICDiskKit takenSpace] floatValue]/totalMem * 100];
    self.headerView.spacePercentLabel.text = [NSString stringWithFormat:@"%@/%.0fGB", [ICDiskKit takenSpace], totalMem];
}

// 智能清理
- (IBAction)smartClearAction:(UIButton *)sender {
    [MobClick event:@"smartclean_button"];
    
    // 获取当前App的相册授权状态
    PHAuthorizationStatus authorizationStatus = [PHPhotoLibrary authorizationStatus];
    // 判断授权状态
    if (authorizationStatus == PHAuthorizationStatusAuthorized) {
        // 如果已经授权, 获取图片
        [self manualClearAction:nil];
    }
    // 如果没决定, 弹出指示框, 让用户选择
    else if (authorizationStatus == PHAuthorizationStatusNotDetermined) {
        [PHPhotoLibrary requestAuthorization:^(PHAuthorizationStatus status) {
            // 如果用户选择授权, 则获取图片
            if (status == PHAuthorizationStatusAuthorized) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    [self manualClearAction:nil];
                });
            }
        }];
    } else {
        [self noticeAlert];
    }
}

// 开启权限提示
- (void)noticeAlert {
    UIAlertController *alert =
    [UIAlertController alertControllerWithTitle: ICLocalized(@"RequiresAlbumAuthorization") //@"此功能需要相册授权"
                                        message: ICLocalized(@"PleaseTurnOnAuthorizationSwitch") //@"请您在设置系统中打开授权开关"
                                 preferredStyle:UIAlertControllerStyleAlert];
    
    UIAlertAction *left = [UIAlertAction actionWithTitle: ICLocalized(@"Cancel") //@"取消"
                                                   style:UIAlertActionStyleCancel
                                                 handler:nil];
    UIAlertAction *right = [UIAlertAction actionWithTitle: ICLocalized(@"GoToSet") //@"前往设置"
                                                    style:UIAlertActionStyleDefault
                                                  handler:^(UIAlertAction * _Nonnull action) {
        NSURL *url = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
        if (@available(iOS 10.0, *)) {
            [[UIApplication sharedApplication] openURL:url options:@{} completionHandler:nil];
        } else {
            [[UIApplication sharedApplication] openURL:url];
        }
    }];
    [alert addAction:left];
    [alert addAction:right];
    [self presentViewController:alert animated:YES completion:nil];
}

// 手动清理
- (IBAction)manualClearAction:(UIButton *)sender {
 
    WKClearPhotoViewController *vc = [[UIStoryboard storyboardWithName:@"Main" bundle: nil] instantiateViewControllerWithIdentifier:@"WKClearPhotoViewController"];
    vc.modalPresentationStyle = UIModalPresentationOverFullScreen;
    ICNavigationController *navc = [[ICNavigationController alloc] initWithRootViewController:vc];
    navc.modalPresentationStyle = UIModalPresentationOverFullScreen;
    [self presentViewController:navc animated:false completion:nil];
}

#pragma mark collectionView Delegate
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return _dataSource.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    
    SCHomeCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"SCHomeCell" forIndexPath:indexPath];
  
    NSDictionary * dic = _dataSource[indexPath.item];
    
    cell.iconImV.image = [UIImage imageNamed:[dic objectForKey:@"image"]];
    cell.titleLab.text = [dic objectForKey:@"title"];
    cell.detailsLab.text = [dic objectForKey:@"details"];
    
    if (indexPath.item%2!=0) {
        cell.right.hidden = YES;
    }else{
        cell.right.hidden = NO;
    }
    
    if (indexPath.item%2==0) {
        cell.left.hidden = YES;
    }else{
        cell.left.hidden = NO;
    }
    
    if (indexPath.item < 2) {
        cell.top.hidden = YES;
    }else{
        cell.top.hidden = NO;
    }
    
    if (indexPath.item > _dataSource.count-2-1) {
        cell.bottom.hidden = YES;
    }else{
        cell.bottom.hidden = NO;
    }
    
    return cell;
}

- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath{
    if (kind == UICollectionElementKindSectionHeader) {
        SCHomeHeaderView * header = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:@"SCHomeHeaderView" forIndexPath:indexPath];
        header.backgroundColor = [UIColor whiteColor];
        
        self.headerView = header;
        self.headerView.frame = CGRectMake(0, 0, KScreenWidth-20, 151+KScaleWidth(168));
        [self.headerView layoutIfNeeded];
        [self.headerView layoutSubviews];
        self.headerView.smartClearButton.layer.cornerRadius = self.headerView.smartClearButton.frame.size.height/2;
        self.headerView.smartClearButton.radarColor = kMassColor;
        self.headerView.smartClearButton.radarBorderColor = kMassColor;
        [self.headerView.smartClearButton addRadarAnimation];
        [self rotateAction];
        [self getDivceSize];
        
        [self.headerView.smartClearButton addTarget:self action:@selector(smartClearAction:) forControlEvents:(UIControlEventTouchUpInside)];
        [self.headerView.manualButton addTarget:self action:@selector(smartClearAction:) forControlEvents:(UIControlEventTouchUpInside)];
        
        return self.headerView;
    }
    return nil;
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section{
    
    return CGSizeMake(KScreenWidth-20, 151+KScaleWidth(168));
}

-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    
    [collectionView deselectItemAtIndexPath:indexPath animated:YES];
    
    switch (indexPath.row) {
        case 0:
        {
            // 获取当前App的相册授权状态
            PHAuthorizationStatus authorizationStatus = [PHPhotoLibrary authorizationStatus];
            // 判断授权状态
            if (authorizationStatus == PHAuthorizationStatusAuthorized) {
                // 如果已经授权, 获取图片
                ICPhotoManageViewController *managePhotoVC = [[ICPhotoManageViewController alloc] init];
                [self.navigationController pushViewController:managePhotoVC animated:true];
            }
            // 如果没决定, 弹出指示框, 让用户选择
            else if (authorizationStatus == PHAuthorizationStatusNotDetermined) {
                [PHPhotoLibrary requestAuthorization:^(PHAuthorizationStatus status) {
                    // 如果用户选择授权, 则获取图片
                    if (status == PHAuthorizationStatusAuthorized) {
                        dispatch_async(dispatch_get_main_queue(), ^{
                            ICPhotoManageViewController *managePhotoVC = [[ICPhotoManageViewController alloc] init];
                            [self.navigationController pushViewController:managePhotoVC animated:true];
                        });
                    }
                }];
            } else {
                [self noticeAlert];
            }
        }
            break;
        case 1:
        {
            ICCalendarManageController *calendarVC = [[ICCalendarManageController alloc] init];
            [self.navigationController pushViewController:calendarVC animated:true];
        }
            break;
        case 2:
        {
            if ([ICUserManager shared].isMember) {
                ICCleanDustViewController *vc = [[UIStoryboard storyboardWithName:@"Main" bundle: nil] instantiateViewControllerWithIdentifier:@"ICCleanDustViewController"];
                [self.navigationController pushViewController:vc animated:true];
            }else {
                ICIAPViewController *iapVC = [[UIStoryboard storyboardWithName:@"Main" bundle: nil] instantiateViewControllerWithIdentifier:@"ICIAPViewController"];
                ICNavigationController *navc = [[ICNavigationController alloc] initWithRootViewController:iapVC];
                [self presentViewController:navc animated:true completion:nil];
            }
        }
            break;
        case 3:
        {
            if ([ICUserManager shared].isMember) {
                ICNetworkSpeedViewController *vc = [[UIStoryboard storyboardWithName:@"Main" bundle: nil] instantiateViewControllerWithIdentifier:@"ICNetworkSpeedViewController"];
                [self.navigationController pushViewController:vc animated:true];
            }else {
                ICIAPViewController *iapVC = [[UIStoryboard storyboardWithName:@"Main" bundle: nil] instantiateViewControllerWithIdentifier:@"ICIAPViewController"];
                ICNavigationController *navc = [[ICNavigationController alloc] initWithRootViewController:iapVC];
                [self presentViewController:navc animated:true completion:nil];
            }
        }
            break;
        case 4:
        {
            if ([ICUserManager shared].isMember) {
                ICDbTestViewController *vc = [[UIStoryboard storyboardWithName:@"Main" bundle: nil] instantiateViewControllerWithIdentifier:@"ICDbTestViewController"];
                [self.navigationController pushViewController:vc animated:true];
            }else {
                ICIAPViewController *iapVC = [[UIStoryboard storyboardWithName:@"Main" bundle: nil] instantiateViewControllerWithIdentifier:@"ICIAPViewController"];
                ICNavigationController *navc = [[ICNavigationController alloc] initWithRootViewController:iapVC];
                [self presentViewController:navc animated:true completion:nil];
            }
        }
            break;
        case 5:
        {
            if ([ICUserManager shared].isMember) {
                ICBatteryCareViewController *vc = [[ICBatteryCareViewController alloc] init];
                [self.navigationController pushViewController:vc animated:true];
            }else {
                ICIAPViewController *iapVC = [[UIStoryboard storyboardWithName:@"Main" bundle: nil] instantiateViewControllerWithIdentifier:@"ICIAPViewController"];
                ICNavigationController *navc = [[ICNavigationController alloc] initWithRootViewController:iapVC];
                [self presentViewController:navc animated:true completion:nil];
            }
        }
            break;
//        case 7:{
//            StatisticsViewController * statistics = [[StatisticsViewController alloc] init];
//            [self.navigationController pushViewController:statistics animated:YES];
//        }
            break;
        default:
            break;
    }
}

@end
