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

#import "ICContactIncompleteController.h"
#import <ContactsUI/ContactsUI.h>
#import "ICContactsIncompleteCell.h"
#import "ICContactListModel.h"
#import "Masonry.h"
#import "ICContactsTool.h"

static NSString * const ICContactsIncompleteCellID = @"ICContactsIncompleteCellID";
@interface ICContactIncompleteController () <UITableViewDataSource, UITableViewDelegate>

@property (nonatomic, strong) UITableView *tableView;
@property(nonatomic,strong)NSMutableArray *dataArray;
@property(nonatomic,strong)UIButton *deleteButton;


@end

@implementation ICContactIncompleteController

-(NSMutableArray *)dataArray
{
    if (!_dataArray) {
        _dataArray = [[NSMutableArray alloc] init];
    }
    return _dataArray;
}

- (void)viewDidLoad {
    [super viewDidLoad];

    [self setupUI];
    [self groupsSources];
}

-(void)setupUI
{
    self.navigationItem.title = ICLocalized(@"AddressInComplete");
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:ICLocalized(@"ChooseAll") style:UIBarButtonItemStyleDone target:self action:@selector(chooseAction)];

    self.tableView = [[UITableView alloc] initWithFrame: self.view.bounds style: UITableViewStylePlain];
    [self.view addSubview:self.tableView];
    
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.rowHeight = 90;
    self.tableView.tableFooterView = [[UIView alloc] init];
    [self.tableView setSeparatorStyle:UITableViewCellSeparatorStyleNone];
    
    [self.tableView registerNib:[UINib nibWithNibName:@"ICContactsIncompleteCell" bundle:nil] forCellReuseIdentifier:ICContactsIncompleteCellID];
        
    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);
    }];
    
}

-(void)groupsSources
{
    [self.dataArray removeAllObjects];
    for (CNContact *con in self.contacts) {
        ICContactListModel *model = [ICContactListModel new];
        model.contact = con;
        model.choose = NO;
        [self.dataArray addObject:model];
    }
    
    [self.tableView reloadData];
}

-(void)deleteAction
{
    [MobClick event:@"contact_incomplete_delete_all"];
    NSInteger idx = 0;
    for (ICContactListModel *model in self.dataArray) {
        if (model.choose) {
            idx ++;
        }
    }
    
//    NSString *key = [NSString stringWithFormat:@"%ld",(long)[[ICContactsTool shareInstance] getCurrentDay]];
//    NSUbiquitousKeyValueStore *keyValueStore = [NSUbiquitousKeyValueStore defaultStore];
//    NSString *count = [keyValueStore objectForKey:[NSString stringWithFormat:@"delete_%@",key]];

    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:ICLocalized(@"Cancel") style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
    }];
    NSString *delete = [NSString stringWithFormat:@"%@(%ld)",ICLocalized(@"Delete"),(long)idx];
    UIAlertAction *sureAction = [UIAlertAction actionWithTitle:delete style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
       [MobClick event:@"contact_incomplete_delete_select"];
//       if ([count integerValue] > 0) {
//           if (idx > [count integerValue]) {
//               [MBProgressHUD showMessage:[NSString stringWithFormat:@"剩余删除次数为%@",count]];
//               return ;
//           }else{
//               NSString *value = [NSString stringWithFormat:@"%ld",(long)[count integerValue] - idx];
//               [keyValueStore setObject:value forKey:[NSString stringWithFormat:@"delete_%@",key]];
//               [keyValueStore synchronize];
//           }
//       }else{
//           [MBProgressHUD showMessage:@"剩余删除次数为0"];
//           return ;
//       }
       
       for (ICContactListModel *model in self.dataArray) {
           if (model.choose) {
               CNMutableContact *contact = (CNMutableContact *)[model.contact mutableCopy];
               [[ICContactsTool shareInstance] deleteContact:contact];
           }
       }
       [self fetchContacts];
   }];
//    NSString *msg = [NSString stringWithFormat:@"每日限制:5\n剩余:%@",count];
   UIAlertController *alert = [UIAlertController alertControllerWithTitle:ICLocalized(@"DeleteContact") message:nil preferredStyle:UIAlertControllerStyleActionSheet];
   [alert addAction:cancelAction];
   [alert addAction:sureAction];
   [self presentViewController:alert animated:YES completion:nil];
}

// 查询是否有选中的联系人
-(void)queryChooseContact
{
    self.deleteButton.hidden = YES;
    for (ICContactListModel *model in self.dataArray) {
        if (model.choose) {
            self.deleteButton.hidden = NO;
            break;
        }
    }
}

- (void)fetchContacts {
    self.contacts = [NSMutableArray array];
    NSArray *array = [[ICContactsTool shareInstance] fetchContacts];
    for (CNContact *con in array) {
        if (con.phoneNumbers.count <= 0) {
            [self.contacts addObject:con];
        }
    }
    
    [self groupsSources];
}

-(void)chooseAction
{
    NSString *name = self.navigationItem.rightBarButtonItem.title;
    if ([name isEqualToString:ICLocalized(@"ChooseAll")]) {
        self.navigationItem.rightBarButtonItem.title = ICLocalized(@"CancelAll");
        [self exchangeChooseState:YES];
    }else{
        self.navigationItem.rightBarButtonItem.title = ICLocalized(@"ChooseAll");
        [self exchangeChooseState:NO];
    }
    [self queryChooseContact];
    
    [self.tableView reloadData];
}

-(void)exchangeChooseState:(BOOL)state
{
    for (ICContactListModel *model in self.dataArray) {
        model.choose = state;
    }
    
    [self.tableView reloadData];
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

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

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 0.1;
}

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

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    ICContactsIncompleteCell *cell = [tableView dequeueReusableCellWithIdentifier:ICContactsIncompleteCellID forIndexPath:indexPath];
    [cell setSelectionStyle:UITableViewCellSelectionStyleNone];

    if (self.dataArray.count) {
        ICContactListModel *model = self.dataArray[indexPath.row];
        cell.model = model;
        [cell.chooseBtn addTarget:self action:@selector(cellChooseAction:) forControlEvents:UIControlEventTouchUpInside];
    }
    
    return cell;
}

-(void)cellChooseAction:(UIButton *)sender
{
    ICContactsIncompleteCell *cell = (ICContactsIncompleteCell *)sender.superview.superview.superview;
    NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
//    NSLog(@"点击的是第%ld = row",indexPath.row);
    ICContactListModel *model = self.dataArray[indexPath.row];
    model.choose = !model.choose;
    
    [self queryChooseContact];

    [self.tableView reloadData];
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:true];
    if (self.dataArray.count == 0) return;
    ICContactListModel *model = self.dataArray[indexPath.row];
    //1.创建Contact对象，必须是可变的
    CNContactViewController *contactController = [CNContactViewController viewControllerForContact:model.contact];
//    contactController.delegate = self;
    /// 是否显示打电话、发短信等按钮
    contactController.allowsActions = YES;
    /// 能否修改数据
    contactController.allowsEditing = YES;
    /// 是否显示联系人的关联联系人
    contactController.shouldShowLinkedContacts = true;
    [contactController viewDidLoad];
    UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController: contactController];
    UIButton *cancelBtn = [UIButton buttonWithType: UIButtonTypeSystem];
    [cancelBtn setTitle:ICLocalized(@"Cancel") forState: UIControlStateNormal];
    cancelBtn.titleLabel.font = [UIFont systemFontOfSize:17];
    [cancelBtn addTarget:self action:@selector(dismissContactController) forControlEvents:UIControlEventTouchUpInside];
    contactController.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView: cancelBtn];

    nav.modalPresentationStyle =  UIModalPresentationFormSheet;
    [self presentViewController:nav animated:YES completion:nil];

}

- (void)dismissContactController {
    [self.navigationController dismissViewControllerAnimated:true completion:nil];
}

@end
