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

#import "ICContactListViewController.h"
#import <ContactsUI/ContactsUI.h>
#import "BMChineseSort.h"
#import "ICContactsListCell.h"
#import "ICContactListModel.h"
#import "Masonry.h"
#import "ICContactsTool.h"

static NSString * const ICContactsListCellID = @"ICContactsListCellID";
@interface ICContactListViewController () <UITableViewDataSource, UITableViewDelegate, CNContactViewControllerDelegate,UISearchResultsUpdating>

@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, copy) NSArray *keys;
@property (nonatomic, strong) CNContactStore *contactStore;
@property(nonatomic,strong)NSMutableArray *firstLetterArray;
@property(nonatomic,strong)NSMutableArray *sortedModelArr;
@property(nonatomic,assign)NSInteger chooseCount;
@property(nonatomic,strong)UIButton *deleteButton;
@property (strong, nonatomic)UISearchController *searchController;
@property(nonatomic,strong)NSMutableArray *searchArray;


@end

@implementation ICContactListViewController

-(NSMutableArray *)searchArray
{
    if (!_searchArray) {
        _searchArray = [NSMutableArray array];
    }
    return _searchArray;
}

-(NSMutableArray *)firstLetterArray
{
    if (!_firstLetterArray) {
        _firstLetterArray = [NSMutableArray array];
    }
    return _firstLetterArray;
}

-(NSMutableArray *)sortedModelArr
{
    if (!_sortedModelArr) {
        _sortedModelArr = [NSMutableArray array];
    }
    return _sortedModelArr;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.navigationItem.title = ICLocalized(@"Contacts");

    [self setupUI];
    [self groupsSources];
}

-(void)setupUI
{
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:ICLocalized(@"Choose") 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 = 50;
    self.tableView.tableFooterView = [[UIView alloc] init];
    [self.tableView registerNib:[UINib nibWithNibName:@"ICContactsListCell" bundle:nil] forCellReuseIdentifier:ICContactsListCellID];
    
    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 setupSearchBar];
}

-(void)setupSearchBar
{
    _searchController = [[UISearchController alloc]initWithSearchResultsController:nil];
    //设置代理
    _searchController.searchResultsUpdater = self;
    //设置UISearchController的显示属性，以下3个属性默认为YES
    //搜索时，背景变暗色
    _searchController.dimsBackgroundDuringPresentation = NO;
    //搜索时，背景变模糊
    _searchController.obscuresBackgroundDuringPresentation = NO;
    //隐藏导航栏
    _searchController.hidesNavigationBarDuringPresentation = YES;
    _searchController.searchBar.backgroundColor = [UIColor whiteColor];
    _searchController.searchBar.searchBarStyle = UISearchBarStyleMinimal;
    _searchController.searchBar.placeholder = ICLocalized(@"Name");
    _searchController.searchBar.frame = CGRectMake(self.searchController.searchBar.frame.origin.x, self.searchController.searchBar.frame.origin.y, self.searchController.searchBar.frame.size.width, 74.0);

    self.tableView.tableHeaderView = _searchController.searchBar;
}

-(void)deleteAction {
    if ([ICUserManager shared].isMember) {
        NSInteger idx = 0;
        for (NSArray *arr in self.sortedModelArr) {
            for (ICContactListModel *model in arr) {
                if (model.choose) {
                    idx ++;
                }
            }
        }
        if (idx == 0) {
            return;
        }
        UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:ICLocalized(@"Cancel") style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
            
            [self cancelAction];
        }];
        UIAlertAction *sureAction = [UIAlertAction actionWithTitle:ICLocalized(@"Delete") style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            [MobClick event:@"contact_delete_action"];
            for (NSArray *arr in self.sortedModelArr) {
                for (ICContactListModel *model in arr) {
                    if (model.choose) {
                        CNMutableContact *contact = (CNMutableContact *)[model.contact mutableCopy];
                        [[ICContactsTool shareInstance] deleteContact:contact];
                    }
                }
            }
            
            [self fetchContacts];
        }];

        NSString *title = [NSString stringWithFormat:@"%@ %ld %@",ICLocalized(@"Delete"),(long)idx,ICLocalized(@"ContactCount")];
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:title message:ICLocalized(@"DeleteDescription") preferredStyle:UIAlertControllerStyleAlert];
        [alert addAction:cancelAction];
        [alert addAction:sureAction];
        [self presentViewController:alert animated:YES completion:nil];
        
    } else {
        ICIAPViewController *iapVC = [[UIStoryboard storyboardWithName:@"Main" bundle: nil] instantiateViewControllerWithIdentifier:@"ICIAPViewController"];
        ICNavigationController *navc = [[ICNavigationController alloc] initWithRootViewController:iapVC];
        [self presentViewController:navc animated:true completion:nil];
    }
}

-(void)chooseAction
{
    self.chooseCount ++;
    NSString *name = self.navigationItem.rightBarButtonItem.title;

    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:ICLocalized(@"Cancel") style:UIBarButtonItemStyleDone target:self action:@selector(cancelAction)];
    if (self.chooseCount > 1 && [name isEqualToString:ICLocalized(@"ChooseAll")]) {
        self.navigationItem.rightBarButtonItem.title = ICLocalized(@"CancelAll");
        [self exchangeChooseState:YES];
    }else{
        self.navigationItem.rightBarButtonItem.title = ICLocalized(@"ChooseAll");
        [self exchangeChooseState:NO];
    }
    self.deleteButton.hidden = NO;
    
    [self.tableView reloadData];
}

// 更改联系人状态
-(void)exchangeChooseState:(BOOL)state
{
    for (NSArray *arr in self.sortedModelArr) {
        for (ICContactListModel *model in arr) {
            model.choose = state;
        }
    }
    [self.tableView reloadData];
}

-(void)cancelAction
{
    [MobClick event:@"contact_delete_action"];
    self.chooseCount = 0;
    self.deleteButton.hidden = YES;
    self.navigationItem.leftBarButtonItem = nil;
    self.navigationItem.rightBarButtonItem.title = ICLocalized(@"Choose");
    [self exchangeChooseState:NO];
    [self.tableView reloadData];
}

// 排序
-(void)groupsSources
{
    [self.firstLetterArray removeAllObjects];
    [self.sortedModelArr removeAllObjects];
    [BMChineseSort sortAndGroup:self.contacts key:@"familyName" finish:^(bool isSuccess, NSMutableArray *unGroupedArr, NSMutableArray *sectionTitleArr, NSMutableArray<NSMutableArray *> *sortedObjArr) {
        if (isSuccess) {
            self.firstLetterArray = sectionTitleArr;
            
            for (NSArray *arr in sortedObjArr) {
                NSMutableArray *modelArr = [[NSMutableArray alloc] init];
                for (CNContact *con in arr) {
                    ICContactListModel *model = [ICContactListModel new];
                    model.contact = con;
                    model.choose = NO;
                    [modelArr addObject:model];
                }
                [self.sortedModelArr addObject:modelArr];
            }
            
            [self.tableView reloadData];
        }
    }];
}

-(void)updateSearchResultsForSearchController:(UISearchController *)searchController
{
    NSLog(@"%@",searchController.searchBar.text);
     CNContactStore *store = [[CNContactStore alloc] init];
        CNContactFetchRequest *fetchRequest = [[CNContactFetchRequest alloc] initWithKeysToFetch: [self keys]];
    fetchRequest.predicate = [CNContact predicateForContactsMatchingName:searchController.searchBar.text];
    [self.searchArray removeAllObjects];
    NSMutableArray *arr = @[].mutableCopy;
    [store enumerateContactsWithFetchRequest:fetchRequest error:nil usingBlock:^(CNContact * _Nonnull contact, BOOL * _Nonnull stop) {
        [arr addObject:contact];
    }];
    for (CNContact *con in arr) {
        ICContactListModel *model = [ICContactListModel new];
        model.contact = con;
        model.choose = NO;
        [self.searchArray addObject:model];
    }
    
    [self.tableView reloadData];
}

//section的titleHeader
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
    if (self.searchController.active) {
        return nil;
    }
    return self.firstLetterArray[section];
}
//section行数
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    if (self.searchController.active) {
        return 1;
    }
    return self.firstLetterArray.count;
}
//每组section个数
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (self.searchController.active) {
        return self.searchArray.count;
    }
    return [self.sortedModelArr[section] count];
}
//section右侧index数组
-(NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView{
    if (self.searchController.active) {
        return @[];
    }
    return self.firstLetterArray;
}
//点击右侧索引表项时调用 索引与section的对应关系
- (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index{
    return index;
}

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

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 30;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 50;
}

//返回cell
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    ICContactsListCell *cell = [tableView dequeueReusableCellWithIdentifier:ICContactsListCellID];
    if (self.searchController.active) {
        if (self.searchArray.count) {
            ICContactListModel *model = self.searchArray[indexPath.row];
            cell.model = model;
            cell.chooseCount = self.chooseCount;
            [cell.chooseBtn addTarget:self action:@selector(cellChooseAction:) forControlEvents:UIControlEventTouchUpInside];

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

-(void)cellChooseAction:(UIButton *)sender
{
    [MobClick event:@"contact_select_action"];
    ICContactsListCell *cell = (ICContactsListCell *)sender.superview.superview;
    NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
//    NSLog(@"点击的是第%ld = section，第%ld = row",indexPath.section,indexPath.row);
    if (self.searchController.active) {
        ICContactListModel *model = self.searchArray[indexPath.row];
        model.choose = !model.choose;
    }else{
        ICContactListModel *model = self.sortedModelArr[indexPath.section][indexPath.row];
        model.choose = !model.choose;
    }
    
    [self.tableView reloadData];
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:true];
    
    ICContactListModel *model;
    if (self.searchController.active) {
        model = self.searchArray[indexPath.row];
    }else{
        model = self.sortedModelArr[indexPath.section][indexPath.row];
    }
    self.searchController.active = NO;

    //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.titleLabel.font = [UIFont systemFontOfSize:17];
    [cancelBtn setTitle:@"取消" forState: UIControlStateNormal];
    [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];
    [self.navigationController pushViewController:contactController animated:YES];
}

- (void)dismissContactController {
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark -- CNContactPickerDelegate
/*!
 * @abstract    Called when the user selects a single property.
 * @discussion  Return @c NO if you do not want anything to be done or if you are handling the actions yourself.
 * @return      @c YES if you want the default action performed for the property otherwise return @c NO.
 */
- (BOOL)contactViewController:(CNContactViewController *)viewController shouldPerformDefaultActionForContactProperty:(CNContactProperty *)property {
    
    return true;
}

/*!
 * @abstract    Called when the view has completed.
 * @discussion  If creating a new contact, the new contact added to the contacts list will be passed.
 *              If adding to an existing contact, the existing contact will be passed.
 * @note        It is up to the delegate to dismiss the view controller.
 */
- (void)contactViewController:(CNContactViewController *)viewController didCompleteWithContact:(nullable CNContact *)contact {

}

- (NSArray *)keys
{
    if (!_keys) {
        _keys = @[[CNContactFormatter descriptorForRequiredKeysForStyle:CNContactFormatterStyleFullName],
                  CNContactPhoneNumbersKey,
                  CNContactOrganizationNameKey,
                  CNContactDepartmentNameKey,
                  CNContactJobTitleKey,
                  CNContactPhoneticGivenNameKey,
                  CNContactPhoneticFamilyNameKey,
                  CNContactPhoneticMiddleNameKey,
                  CNContactImageDataKey,
                  CNContactThumbnailImageDataKey,
                  CNContactEmailAddressesKey,
                  CNContactPostalAddressesKey,
                  CNContactBirthdayKey,
                  CNContactNonGregorianBirthdayKey,
                  CNContactInstantMessageAddressesKey,
                  CNContactSocialProfilesKey,
                  CNContactRelationsKey,
                  CNContactUrlAddressesKey, CNContactViewController.descriptorForRequiredKeys];
        
    }
    return _keys;
}

- (void)fetchContacts {
    self.contacts = [NSMutableArray array];
    NSArray *contacts = [[ICContactsTool shareInstance] fetchContacts];
    [self.contacts addObjectsFromArray:contacts];
    [self groupsSources];
}



@end
