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

#import "ICCalenderEventViewController.h"
#import "WMEventCalendarTool.h"
#import "ICCalendarEventViewCell.h"
#import "ICContactsIncompleteCell.h"

@interface ICCalenderEventViewController ()<UITableViewDataSource, UITableViewDelegate>

@property (nonatomic, strong) UITableView *tableView;
/// 联系人
@property (nonatomic, strong) NSMutableArray<EKEvent *> *events;
@property (nonatomic, strong) NSMutableArray *selectedItems;
@property (nonatomic, strong) UIButton *deleteButton;
@property (nonatomic, assign) BOOL isSelectedAll;
@property (nonatomic, strong) UIButton *selectAllButton;

@end

@implementation ICCalenderEventViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.selectedItems = [NSMutableArray array];
    
    self.navigationItem.title = ICLocalized(@"Manage Calendar");
    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.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.rowHeight = 90;
    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];
    //[[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 fetchCalendarEvents];
    
}

-(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) {
            EKEvent *event = self.events[[index intValue]];
            [[WMEventCalendarTool sharedCalendar] deleteCalendarEvent: event];
            if ([self.selectedItems containsObject:index]) {
                [self.selectedItems removeObject:index];
            }
        }
        [self fetchCalendarEvents];
    }];
    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.events.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)fetchCalendarEvents {
    [[WMEventCalendarTool sharedCalendar] checkCalendarCanUsedCompletion:^(BOOL granted, NSError *error) {
        if (granted) {
            NSArray *events = [[WMEventCalendarTool sharedCalendar] checkToStartDate:[NSDate dateWithTimeIntervalSince1970:1514375207] addEndDate: [NSDate date] addModifytitle:nil addCalendarIdentifier: nil];
            self.events = events.mutableCopy;
            [self.tableView reloadData];
            [self updateDeleteButtonStatus];
//            for (int i = 0; i < events.count; i++) {
//                EKEvent *event = events[i];
//                NSLog(@"%@ - %@",event.title,event.eventIdentifier);
//            }
        } 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.events.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 configWithEvent:self.events[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];
    
    //EKEvent *event = self.events[indexPath.row];

//    }
//    if ([[WMEventCalendarTool sharedCalendar] deleteCalendarEvent: event]) {
//        [self fetchCalendarEvents];
//    }
}


@end
