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

#import "ICContactRepeatViewController.h"
#import <ContactsUI/ContactsUI.h>
#import "ICContactsRepeatCell.h"
#import "Masonry.h"
#import "ICContactListModel.h"
#import "ICContactsRepeatHeader.h"
#import "ICContactsTool.h"

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

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

@end

@implementation ICContactRepeatViewController

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

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.

    [self setupUI];
}

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

    self.tableView = [[UITableView alloc] initWithFrame: self.view.bounds style: UITableViewStyleGrouped];
    [self.view addSubview:self.tableView];
    self.tableView.backgroundColor = [UIColor whiteColor];
    self.tableView.showsVerticalScrollIndicator = NO;
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.rowHeight = 90;
    [self.tableView setSeparatorStyle:UITableViewCellSeparatorStyleNone];
    [self.tableView registerNib:[UINib nibWithNibName:@"ICContactsRepeatCell" bundle:nil] forCellReuseIdentifier:ICContactsRepeatCellID];
    [self.tableView registerClass:[ICContactsRepeatHeader class] forHeaderFooterViewReuseIdentifier:@"header"];
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(@16);
        make.right.equalTo(@(-16));
        make.top.bottom.equalTo(@0);
    }];
    
    self.mergeButton = [UIButton buttonWithType:UIButtonTypeCustom];
       [self.mergeButton setTitle:ICLocalized(@"Merge") forState:UIControlStateNormal];
       [self.mergeButton setBackgroundImage:[UIImage imageNamed:@"global_green_btn_bg"] forState:UIControlStateNormal];
       [self.mergeButton addTarget:self action:@selector(mergeAction) forControlEvents:UIControlEventTouchUpInside];
       [self.view addSubview:self.mergeButton];
       self.mergeButton.hidden = YES;
       [self.mergeButton mas_makeConstraints:^(MASConstraintMaker *make) {
           make.centerX.equalTo(self.view);
           make.bottom.equalTo(@(-40));
           make.height.equalTo(@62);
           make.width.equalTo(@343);
       }];
    
    [self.dataArray removeAllObjects];
    for (NSArray *arr in self.dataSoruce) {
        NSMutableArray *modelArr = [[NSMutableArray alloc] init];
        for (CNContact *con in arr) {
            ICContactListModel *model = [ICContactListModel new];
            model.contact = con;
            model.choose = NO;
            [modelArr addObject:model];
        }
        [self.dataArray addObject:modelArr];
    }
    
    [self.tableView reloadData];
}

-(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)queryChooseContact
{
    self.mergeButton.hidden = YES;
    NSInteger idx = 0;
    for (NSArray *arr in self.dataArray) {
        for (ICContactListModel *model in arr) {
            if (model.choose) {
                idx ++;
                if (idx > 1) {
                    self.mergeButton.hidden = NO;
                    break;
                }
            }
        }
    }
}

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

-(void)mergeAction
{
    [MobClick event:@"contact_repeat_combine"];
//    NSString *key = [NSString stringWithFormat:@"%ld",(long)[[ICContactsTool shareInstance] getCurrentDay]];
//    NSUbiquitousKeyValueStore *keyValueStore = [NSUbiquitousKeyValueStore defaultStore];
//    NSString *count = [keyValueStore objectForKey:[NSString stringWithFormat:@"merge_%@",key]];

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

- (void)fetchContacts {
    NSMutableArray *contacts = [NSMutableArray array];
    NSArray *array = [[ICContactsTool shareInstance] fetchContacts];
    [contacts addObjectsFromArray:array];
    
    NSMutableArray *contArrays = [NSMutableArray array];
    for (NSArray *arr in [self groupAction: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 (![contArrays containsObject:temp] && temp.count) {
                [contArrays addObject:temp];
            }
        }
        
        [self.dataArray removeAllObjects];
        for (NSArray *arr in contArrays) {
            NSMutableArray *modelArr = [[NSMutableArray alloc] init];
            for (CNContact *con in arr) {
                ICContactListModel *model = [ICContactListModel new];
                model.contact = con;
                model.choose = NO;
                [modelArr addObject:model];
            }
            [self.dataArray addObject:modelArr];
        }
    }
    
    [self.tableView reloadData];
}

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

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

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

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

-(void)selectAllAction:(UIButton *)sender
{
    BOOL flag;
    if ([sender.titleLabel.text isEqualToString:ICLocalized(@"CancelAll")]) {
        flag = NO;
    }else{
        flag = YES;
    }
    NSArray *array = self.dataArray[sender.tag];
    for (ICContactListModel *model in array) {
        model.choose = flag;
    }
    
    [self queryChooseContact];
    
    [self.tableView reloadData];
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    ICContactsRepeatHeader *header = [tableView dequeueReusableHeaderFooterViewWithIdentifier:@"header"];
    [header.selectBtn addTarget:self action:@selector(selectAllAction:) forControlEvents:UIControlEventTouchUpInside];
    header.selectBtn.tag = section;
    header.contacts = self.dataArray[section];
    
//    NSArray *array = self.dataArray[section];
//    NSString *name = @"";
//    NSString *phone = @"";
//    NSString *subPhone = @"";
//    NSInteger idx = 0;
//    [header.selectBtn setTitle:@"取消全选" forState:UIControlStateNormal];
//    for (ICContactListModel *model in array) {
//        subPhone = [subPhone stringByAppendingFormat:@"%@ ",model.contact.familyName];
//        if (model.contact.phoneNumbers.count) {
//            NSArray *phones = model.contact.phoneNumbers;
//            CNLabeledValue *labeledValue = phones[0];
//            CNPhoneNumber *phoneNumer = labeledValue.value;
//            NSString *phoneNumber = phoneNumer.stringValue;
//            phone = [NSString stringWithFormat:@"%@", phoneNumber];
//        }
//        if (model.choose) {
//            idx ++;
//            name = [name stringByAppendingFormat:@"%@ ",model.contact.familyName];
//        }else{
//            [header.selectBtn setTitle:@"选择全部" forState:UIControlStateNormal];
//        }
//    }
//    if (idx > 1) {
//        [header updateName:name updatePhone:phone];
//    }else{
//        [header updateName:subPhone updatePhone:phone];
//    }
//
    return header;
}

-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    UIView *v = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width - 32, 15)];
    v.backgroundColor = kMassColorAlpha(0.15);
    UIBezierPath *maskPath = [UIBezierPath bezierPathWithRoundedRect:v.bounds byRoundingCorners:UIRectCornerBottomLeft|UIRectCornerBottomRight cornerRadii:CGSizeMake(8, 8)];
    CAShapeLayer *maskLayer = [CAShapeLayer layer];
    maskLayer.frame = v.bounds;
    maskLayer.path = maskPath.CGPath;
    v.layer.mask = maskLayer;
    
    return v;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    ICContactsRepeatCell *cell = [tableView dequeueReusableCellWithIdentifier:ICContactsRepeatCellID forIndexPath:indexPath];
    [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
    
    if (self.dataArray.count) {
        ICContactListModel *model = self.dataArray[indexPath.section][indexPath.row];
        cell.model = model;
        [cell.chooseButton addTarget:self action:@selector(cellChooseAction:) forControlEvents:UIControlEventTouchUpInside];
    }
    
    return cell;
}

-(void)cellChooseAction:(UIButton *)sender
{
    ICContactsRepeatCell *cell = (ICContactsRepeatCell *)sender.superview.superview.superview.superview;
    NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
//    NSLog(@"点击的是第%ld = section，第%ld = row",indexPath.section,indexPath.row);
    ICContactListModel *model = self.dataArray[indexPath.section][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.section][indexPath.row];
    [[ICContactsTool shareInstance] enterContactsDetail:model.contact controller:self push:NO];
}

//对返回的数据进行区分筛选
- (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;

}

@end
