//
//  ICCalenderReminderController.m
//  superCleaner
//
//  Created by Mazy on 2020/7/29.
//  Copyright © 2020 Mazy. All rights reserved.
//

#import "ICCalenderReminderController.h"
#import "WMEventCalendarTool.h"
#import "ICContactsIncompleteCell.h"

@interface ICCalenderReminderController ()<UITableViewDataSource, UITableViewDelegate>
@property (nonatomic, strong) UITableView *tableView;
/// 联系人
@property (nonatomic, strong) NSMutableArray<EKReminder *> *reminders;
@property (nonatomic, strong) NSMutableArray *selectedItems;
@property (nonatomic, strong) UIButton *deleteButton;
@property (nonatomic, assign) BOOL isSelectedAll;
@property (nonatomic, strong) UIButton *selectAllButton;

@end

@implementation ICCalenderReminderController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.selectedItems = [NSMutableArray array];
    
    self.navigationItem.title = ICLocalized(@"ManageReminders"); //@"提醒事项管理";
    
    self.tableView = [[UITableView alloc] initWithFrame: self.view.bounds style: UITableViewStylePlain];
    [self.view addSubview:self.tableView];
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.view);
    }];
    
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.rowHeight = 90;
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView.tableFooterView = [[UIView alloc] init];
    self.tableView.contentInset = UIEdgeInsetsMake(10, 0, 100, 0);
    [self.tableView registerNib: [UINib nibWithNibName:@"ICContactsIncompleteCell" bundle:nil] forCellReuseIdentifier:@"ICContactsIncompleteCell"];
    
    self.selectAllButton = [[UIButton alloc] init];
    [self.selectAllButton setTitle: ICLocalized(@"ChooseAll") forState:UIControlStateNormal];
    [self.selectAllButton addTarget:self action: @selector(chooseAction) forControlEvents:UIControlEventTouchUpInside];
    [self.selectAllButton setTitleColor:UIColor.blackColor forState: UIControlStateNormal];
    self.selectAllButton.titleLabel.font = [UIFont systemFontOfSize:17];
    [self.selectAllButton sizeToFit];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView: self.selectAllButton];
//    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:ICLocalized(@"ChooseAll") style:UIBarButtonItemStyleDone target:self action:@selector(chooseAction)];
    
    self.deleteButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.deleteButton setTitle:ICLocalized(@"DeleteSelected") forState:UIControlStateNormal];
    [self.deleteButton setBackgroundImage:[UIImage imageNamed:@"global_green_btn_bg"] forState:UIControlStateNormal];
    [self.deleteButton addTarget:self action:@selector(deleteAction) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.deleteButton];
    self.deleteButton.hidden = YES;
    [self.deleteButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.view);
        make.bottom.equalTo(@(-40));
        make.height.equalTo(@62);
        make.width.equalTo(@343);
    }];
    
    [self fetchCalendarReminders];
}

-(void)deleteAction {
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:ICLocalized(@"Cancel") style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
    }];
    UIAlertAction *sureAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        for (NSNumber *index in self.selectedItems.mutableCopy) {
            EKReminder *event = self.reminders[[index intValue]];
            [[WMEventCalendarTool sharedCalendar] deleteCompletedReminder: event];
            if ([self.selectedItems containsObject:index]) {
                [self.selectedItems removeObject:index];
            }
        }
        [self fetchCalendarReminders];
    }];
    NSString *delete = [NSString stringWithFormat:@"确定要删除%ld条日历提醒吗?",(long)self.selectedItems.count];
    UIAlertController *alert = [UIAlertController alertControllerWithTitle: @"温馨提示" message:delete preferredStyle:UIAlertControllerStyleAlert];
    [alert addAction:cancelAction];
    [alert addAction:sureAction];
    [self presentViewController:alert animated:YES completion:nil];
}

-(void)chooseAction {
    
    self.isSelectedAll = !self.isSelectedAll;
    [self.selectedItems removeAllObjects];
    if (self.isSelectedAll) {
        for (int i = 0; i < self.reminders.count; i++) {
            [self.selectedItems addObject:@(i)];
        }
        [self.selectAllButton setTitle:ICLocalized(@"CancelAll") forState:UIControlStateNormal];
    } else {
        [self.selectAllButton setTitle:ICLocalized(@"ChooseAll") forState:UIControlStateNormal];
    }
    
    [self updateDeleteButtonStatus];
    [self.tableView reloadData];
}

// 查询是否有选中
-(void)updateDeleteButtonStatus {
    self.deleteButton.hidden = self.selectedItems.count <= 0;
}

- (void)fetchCalendarReminders {
    
    [[WMEventCalendarTool sharedCalendar] checkCalendarReminderCanUsedCompletion:^(BOOL granted, NSError *error) {
        if (granted) {
            [[WMEventCalendarTool sharedCalendar] checkCompletedRemindersStartDate:[NSDate dateWithTimeIntervalSince1970:1514375207] addEndDate:[NSDate date] fetchCompleted:^(NSArray<EKReminder *> *reminders) {
                
                dispatch_async(dispatch_get_main_queue(), ^{
                    self.reminders = reminders.mutableCopy;
                    [self updateDeleteButtonStatus];
                    [self.tableView reloadData];
                    // EKReminder *event = reminders[i];
//                    for (EKReminder *reminder in reminders) {
//                        NSLog(@"提醒事项 - %@ ",reminder.title);
//                    }
                });
            }];
        } else {
            NSLog(@"需要打开权限");
        }
    }];
}

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


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

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.reminders.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 {
    ICContactsIncompleteCell *cell = [tableView dequeueReusableCellWithIdentifier:@"ICContactsIncompleteCell" forIndexPath:indexPath];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    [cell configWithReminder:self.reminders[indexPath.row] seleted: [self.selectedItems containsObject:@(indexPath.row)]];
    cell.selectedClosure = ^(BOOL granted) {
        if (granted) {
            if (![self.selectedItems containsObject:@(indexPath.row)]) {
                [self.selectedItems addObject:@(indexPath.row)];
            }
        } else {
            if ([self.selectedItems containsObject:@(indexPath.row)]) {
                [self.selectedItems removeObject:@(indexPath.row)];
            }
        }
        [self updateDeleteButtonStatus];
        [self.tableView reloadData];
    };
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:true];
    
    EKReminder *reminder = self.reminders[indexPath.row];
    
    //    if ([[WMEventCalendarTool sharedCalendar] deleteCompletedReminder:reminder]) {
    //        [self fetchCalendarReminders];
    //    }
}

@end
