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

#import "ICContactsViewController.h"
#import "ICContactManageViewCell.h"
#import "ICContactListViewController.h"
#import <Contacts/Contacts.h>
#import <ContactsUI/ContactsUI.h>
#import "ICContactRepeatViewController.h"
#import "ICContactIncompleteController.h"
#import "ICContactBackupController.h"
#import "ICContactsTool.h"
#include <sys/param.h>
#include <sys/mount.h>

@interface ICContactsViewController () <UITableViewDataSource, UITableViewDelegate, CNContactViewControllerDelegate>

@property (nonatomic, strong) UITableView *tableView;
/// 联系人
@property (nonatomic, strong) NSMutableArray<CNContact *> *contacts;
/// 重复联系人
@property (nonatomic, strong) NSMutableArray<NSArray<CNContact *> *> *repeatDataSoruce;
/// 不完整联系人
@property (nonatomic, strong) NSMutableArray<CNContact *> *incompleteContacts;

@end

@implementation ICContactsViewController

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

    BOOL enable = [[ICContactsTool shareInstance] contactsAuthStatus];
    if (enable) {
        CNContactStore *contactStore = [[CNContactStore alloc] init];
        [contactStore requestAccessForEntityType:CNEntityTypeContacts completionHandler:^(BOOL granted, NSError * _Nullable error) {
            if (granted) {
                [self fetchContacts];
                // 成功
            } else {
                // 失败
            }
        }];
    }
}

- (void)viewDidLoad {
    [super viewDidLoad];

    self.navigationItem.title = ICLocalized(@"ManagementContact");
    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.contentInset = UIEdgeInsetsMake(10, 0, 0, 0);
    [self.tableView registerNib: [UINib nibWithNibName:@"ICContactManageViewCell" bundle:nil] forCellReuseIdentifier:@"ICContactManageViewCell"];
    
//    /// 自动备份
//    NSString *value = [[NSUserDefaults standardUserDefaults] objectForKey:@"auto_icloud_backup"];
//    if ([value isEqualToString:@"auto_backup"]) {
//        [[ICContactsTool shareInstance] autoSavesssiCloudFileName:@"001"];
//    }
//
    // 注册删除次数
    [[ICContactsTool shareInstance] registerDeleteOrMergeCount];
}

-(NSString *)convertToJsonData:(NSDictionary *)dict
{
    NSError *error;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:&error];
    NSString *jsonString;
    if (!jsonData) {
        NSLog(@"%@",error);
    }else{
        jsonString = [[NSString alloc]initWithData:jsonData encoding:NSUTF8StringEncoding];
    }
    NSMutableString *mutStr = [NSMutableString stringWithString:jsonString];
    NSRange range = {0,jsonString.length};
    //去掉字符串中的空格
    [mutStr replaceOccurrencesOfString:@" " withString:@"" options:NSLiteralSearch range:range];
    NSRange range2 = {0,mutStr.length};
    //去掉字符串中的换行符
     [mutStr replaceOccurrencesOfString:@"\n" withString:@"" options:NSLiteralSearch range:range2];
    return mutStr;
}

- (void)fetchContacts {
    self.contacts = [NSMutableArray array];
    self.incompleteContacts = [NSMutableArray array];
    NSArray *contacts = [[ICContactsTool shareInstance] fetchContacts];
    [self.contacts addObjectsFromArray:contacts];
    for (CNContact *con in self.contacts) {
        if (con.phoneNumbers.count <= 0) {
            [self.incompleteContacts addObject:con];
        }
    }
        
    self.repeatDataSoruce = [NSMutableArray array];
    for (NSArray *arr in [self groupAction:self.contacts]) {
        if (arr.count > 1) {
            NSMutableArray *temp = [NSMutableArray array];
            for (NSDictionary *dict in arr) {
                CNContact *con = dict[@"contact"];
                if (con.phoneNumbers.count != 0) {
                    [temp addObject:dict[@"contact"]];
                }
            }
            if (![self.repeatDataSoruce containsObject:temp] && temp.count) {
                [self.repeatDataSoruce addObject:temp];
            }
        }
    }
    dispatch_async(dispatch_get_main_queue(), ^{
        [self.tableView reloadData];
    });
}

//对返回的数据进行区分筛选
- (NSMutableArray *)groupAction:(NSMutableArray *)arr {
    __block NSMutableArray *groupArr = [NSMutableArray array];
    NSMutableArray *array = [[NSMutableArray alloc] init];
    for (CNContact *contact in arr) {
        NSArray *phones = contact.phoneNumbers;
        if (phones.count) {
            CNLabeledValue *labeledValue = phones[0];
            CNPhoneNumber *phoneNumer = labeledValue.value;
            NSString *phoneNumber = phoneNumer.stringValue;
            if (phoneNumber.length) {
                [array addObject:@{@"phoneNumber":phoneNumber,@"contact":contact}];
            }else{
                [array addObject:@{@"phoneNumber":@"number",@"contact":contact}];
            }
        }else{
            [array addObject:@{@"phoneNumber":@"number",@"contact":contact}];
        }
    }
    
    [array enumerateObjectsUsingBlock:^(NSDictionary *obj, NSUInteger idx, BOOL * _Nonnull stop) {
        NSString *phoneNumber = obj[@"phoneNumber"];
        NSPredicate *predicate = [NSPredicate predicateWithFormat:@"phoneNumber = %@", phoneNumber];
        NSArray *tempArr = [NSArray arrayWithArray:[array filteredArrayUsingPredicate:predicate]];
        [groupArr addObject:tempArr];
    }];
    
    return groupArr;

}

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

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 2;
}

- (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 {
    ICContactManageViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"ICContactManageViewCell" forIndexPath:indexPath];
    switch (indexPath.section) {
        case 0:
            cell.subTitleLabel.hidden = true;
            switch (indexPath.row) {
                case 0:
                    cell.mainTitleLabel.text = ICLocalized(@"Contacts");
                    cell.countLabel.hidden = false;
                    cell.countLabel.text = [NSString stringWithFormat:@"%lu", (unsigned long)self.contacts.count];
                    break;
                default:
                    cell.countLabel.hidden = true;
                    cell.mainTitleLabel.text = ICLocalized(@"BackupContact");
                    break;
            }
            break;
        default:
            cell.countLabel.hidden = false;
            switch (indexPath.row) {
                case 0:
                    cell.mainTitleLabel.text = ICLocalized(@"Repeat");
                    cell.countLabel.text = [NSString stringWithFormat:@"%lu", (unsigned long)self.repeatDataSoruce.count];
                    cell.subTitleLabel.text = ICLocalized(@"NamePhoneEmail");
                    break;
                default:
                    cell.mainTitleLabel.text = ICLocalized(@"AddressInComplete");
                    cell.countLabel.text = [NSString stringWithFormat:@"%lu", (unsigned long)self.incompleteContacts.count];
                    cell.subTitleLabel.text = ICLocalized(@"NoNamePhoneEmail");
                    break;
            }
            break;
    }
    return cell;
}

/*
     if ([ICUserManager shared].isMember) {
 } else {
     ICIAPViewController *iapVC = [[UIStoryboard storyboardWithName:@"Main" bundle: nil] instantiateViewControllerWithIdentifier:@"ICIAPViewController"];
     ICNavigationController *navc = [[ICNavigationController alloc] initWithRootViewController:iapVC];
     [self presentViewController:navc animated:true completion:nil];
 }
 */
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:true];

    if (indexPath.section == 0 && indexPath.row == 0) {
        ICContactListViewController *listVC = [[ICContactListViewController alloc] init];
        listVC.contacts = self.contacts;
        [self.navigationController pushViewController:listVC animated:true];
    } else if (indexPath.section == 0 && indexPath.row == 1) {
        [MobClick event:@"contact_backup"];
        if ([ICUserManager shared].isMember) {
            ICContactBackupController *listVC = [[ICContactBackupController alloc] init];
            listVC.contacts = self.contacts;
            [self.navigationController pushViewController:listVC 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];
        }
    } else if (indexPath.section == 1 && indexPath.row == 0) {
        [MobClick event:@"contact_repeat_number"];
        if ([ICUserManager shared].isMember) {
            ICContactRepeatViewController *repeatVC = [[ICContactRepeatViewController alloc] init];
            repeatVC.dataSoruce = self.repeatDataSoruce;
            [self.navigationController pushViewController:repeatVC 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];
        }
    } else if (indexPath.section == 1 && indexPath.row == 1) {
        [MobClick event:@"contact_incomplete"];
        if ([ICUserManager shared].isMember) {
            ICContactIncompleteController *incompleteVC = [[ICContactIncompleteController alloc] init];
            incompleteVC.contacts = self.incompleteContacts;
            [self.navigationController pushViewController:incompleteVC 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];
        }
    }
}


@end
