//
//  ICContactsTool.m
//  superCleaner
//
//  Created by GY.Z on 2020/7/6.
//  Copyright © 2020 Mazy. All rights reserved.
//

#import "ICContactsTool.h"
#import <Contacts/Contacts.h>
#import <ContactsUI/ContactsUI.h>
#import "PYHDocument.h"
#import <objc/runtime.h>

#define UbiquityContainerIdentifiers  @"iCloud.com.app.superCleanMaster"
@interface ICContactsTool ()<PYHDocumentDelegate>
{
    NSMetadataQuery *_metaQuery;
}
@property(nonatomic,strong)NSArray *keys;
@property(nonatomic,strong)UIViewController *contactController;
@property(nonatomic,assign)BOOL contactPush;



@end

static ICContactsTool *tool = nil;
@implementation ICContactsTool

+(instancetype)shareInstance
{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        tool = [[ICContactsTool alloc] init];
    });
    
    return tool;
}

-(BOOL)contactsAuthStatus
{
    BOOL isAvalible = NO;
    CNAuthorizationStatus authStatus = [CNContactStore authorizationStatusForEntityType:CNEntityTypeContacts];
    switch (authStatus) {
        case CNAuthorizationStatusAuthorized:
            isAvalible = YES;
            break;
        case CNAuthorizationStatusDenied:
        {
            [MBProgressHUD showMessage:ICLocalized(@"AddressBookOpen")];
            isAvalible = NO;
        }
            break;
        case CNAuthorizationStatusNotDetermined:
        {
            isAvalible = YES;
        }
            break;
        case CNAuthorizationStatusRestricted:
            [MBProgressHUD showMessage: ICLocalized(@"AddressBookOpen")];
            isAvalible = NO;
            break;
    }
    return isAvalible;
}

-(void)synciCloudContactsFileName:(NSString *)fileName
{
    NSArray *contacts = [self fetchContacts];
    [self saveiCloud:contacts fileName:fileName];
}

-(void)loadiCloudDirectory
{
    [_metaQuery stopQuery];
    _metaQuery = nil;
    _metaQuery = [[NSMetadataQuery alloc]init];
    _metaQuery.searchScopes = @[NSMetadataQueryUbiquitousDataScope];
    _metaQuery.notificationBatchingInterval = 15;
    NSOperationQueue *queue = [NSOperationQueue mainQueue];
    _metaQuery.operationQueue = queue;
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(gatherFinish:) name:NSMetadataQueryDidFinishGatheringNotification object:_metaQuery];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(gatherFinish:) name:NSMetadataQueryDidUpdateNotification object:_metaQuery];
    [_metaQuery startQuery];
}

-(void)gatherFinish:(NSNotification*)nofification
{
    NSMetadataQuery *query = nofification.object;
    [query disableUpdates];
    NSLog(@"------resultCount:%lu",(unsigned long)query.resultCount);
    [[NSNotificationCenter defaultCenter] removeObserver:self name:NSMetadataQueryDidFinishGatheringNotification object:query];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:NSMetadataQueryDidUpdateNotification object:query];
    if (query.resultCount > 0) {
        NSArray *result = query.results;
        NSMutableArray *datasource = [NSMutableArray array];
        for (NSMetadataItem *item in result) {
            NSDictionary *dic = [item valuesForAttributes:@[NSMetadataItemFSSizeKey,NSMetadataItemFSNameKey,NSMetadataItemURLKey,NSMetadataItemFSContentChangeDateKey,NSMetadataItemContentTypeKey]];
            [datasource addObject:dic];
//            NSLog(@"%@",item.attributes);
        }
        NSLog(@"datasource = %@",datasource);
        NSMutableArray *temp = [[NSMutableArray alloc] init];
        NSMutableArray *lastArr = [[NSMutableArray alloc] init];
        NSMutableArray *source = [[NSMutableArray alloc] init];
        for (NSDictionary *dict in datasource) {
            if (dict[@"kMDItemFSName"] && [dict[@"kMDItemFSName"] containsString:@"Contacts-"]) {
                [temp addObject:dict];
            }else{
                [lastArr addObject:dict];
            }
        }
        
        for (NSDictionary *dict in temp) {
            NSString *name = dict[@"kMDItemFSName"];
            NSMutableDictionary *dic = [[NSMutableDictionary alloc] init];
            [dic addEntriesFromDictionary:dict];

            for (NSDictionary *dict in lastArr) {
                NSString *kMDItemFSName = dict[@"kMDItemFSName"];
                if ([name containsString:kMDItemFSName]) {
                    dic[@"kMDItemFSSize"] = dict[@"kMDItemFSSize"] ? dict[@"kMDItemFSSize"] : @"0";
                    [source addObject:dic];
                    continue;
                }
            }
            
        }

        
        if (self.delegate && [self.delegate respondsToSelector:@selector(getiCloudList:)]) {
            [self.delegate getiCloudList:source];
        }
    }
    
    [query enableUpdates];
}

-(void)saveiCloud:(NSArray *)contacts fileName:(NSString *)fileName
{
    NSURL *ubiquityURL = [[NSFileManager defaultManager] URLForUbiquityContainerIdentifier:UbiquityContainerIdentifiers];
    //验证iCloud是否可用
    if(!ubiquityURL)
    {
        [MBProgressHUD showMessage: ICLocalized(@"ICloudIsNotEnabled")];
        return;
    }
    if (contacts.count == 0)
    {
        [MBProgressHUD showMessage: ICLocalized(@"EmptyContact")];
        return;
    }
    
    [MBProgressHUD showLoading: ICLocalized(@"BackingUp")];

    NSURL *myContainer = [[NSFileManager defaultManager]
                     URLForUbiquityContainerIdentifier:NSMetadataQueryUbiquitousDataScope];
      
      if (myContainer != nil) {
          NSLog(@"应用可以写入iCloud容器，iCloud容器地址：%@",myContainer);
          NSURL *cloudUrl = [myContainer URLByAppendingPathComponent:[NSString stringWithFormat:@"Contacts-%@",fileName]];
//          NSURL *cloudUrl = [myContainer URLByAppendingPathComponent:@"contacts"];
          NSLog(@"cloudUrl = %@",cloudUrl);
          PYHDocument *document = [[PYHDocument alloc]initWithFileURL:cloudUrl];
          
          //要保存的数据
          document.saveData = [NSKeyedArchiver archivedDataWithRootObject:contacts];;
          document.saveFileName = fileName;
          [document saveToURL:document.fileURL forSaveOperation:UIDocumentSaveForCreating completionHandler:^(BOOL success) {
              if (success) {
                  [MBProgressHUD showSuccess: ICLocalized(@"BackupCompleted")];
              }else{
                  [MBProgressHUD showError: ICLocalized(@"BackupFailedPleaseTryAgain")];
              }
              [document closeWithCompletionHandler:^(BOOL success) {
                  
              }];
          }];
      }
}

-(void)deleteiCloudContactsUrlFile:(NSURL *)urlFile
{
    BOOL flag = [[NSFileManager defaultManager] removeItemAtURL:urlFile error:nil];
    if (flag) {
        NSLog(@"删除成功:urlFile = %@",urlFile.absoluteString);
    }else{
        NSLog(@"删除失败:urlFile = %@",urlFile.absoluteString);
    }

}

-(void)getiCloudContactsPath:(NSURL *)path
{
    PYHDocument *document = [[PYHDocument alloc] initWithFileURL:path];
    document.delegate = self;
    // 打开
    [document openWithCompletionHandler:^(BOOL success) {
        if (success) {
            [MBProgressHUD showSuccess: ICLocalized(@"OpenSuccess")];
        }else{
            [MBProgressHUD showError: ICLocalized(@"FailedOpenTryLater")];
        }
        // 关闭
        [document closeWithCompletionHandler:^(BOOL success) {

        }];
    }];
}

-(void)docGetiCloudContactsMethods:(NSData *)obj fileInfo:(nonnull NSDictionary *)fileInfo
{
    if (self.delegate && [self.delegate respondsToSelector:@selector(getiCloudContactsMethods:fileInfo:)]) {
        [self.delegate getiCloudContactsMethods:obj fileInfo:fileInfo];
    }
}

-(NSArray *)fetchContacts{
    CNContactStore *store = [[CNContactStore alloc] init];
    CNContactFetchRequest *fetchRequest = [[CNContactFetchRequest alloc] initWithKeysToFetch: [self keys]];
    NSMutableArray *contacts = [NSMutableArray array];
    [store enumerateContactsWithFetchRequest:fetchRequest error:nil usingBlock:^(CNContact * _Nonnull contact, BOOL * _Nonnull stop) {
        [contacts addObject:contact];
    }];
    
    return contacts;
}

// 删除联系人
- (void)deleteContact:(CNMutableContact *)contact{
    // 创建联系人请求
    CNSaveRequest *saveRequest = [[CNSaveRequest alloc] init];
    [saveRequest deleteContact:contact];
    // 写入操作
    CNContactStore *store = [[CNContactStore alloc] init];
    [store executeSaveRequest:saveRequest error:nil];
}

// 更新联系人
- (void)updateContact:(CNMutableContact *)contact{
    // 创建联系人请求
    CNSaveRequest *saveRequest = [[CNSaveRequest alloc] init];
    [saveRequest updateContact:contact];
    // 重新写入
    CNContactStore *store = [[CNContactStore alloc] init];
    [store executeSaveRequest:saveRequest error:nil];
}

-(void)archive
{
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
       NSString *documentFilePath = paths.firstObject;
       NSString *filePath = [documentFilePath stringByAppendingPathComponent:@"fetchContacts"];
       
        CNMutableContact *contact = [[CNMutableContact alloc] init];
       contact.givenName = @"san";
       contact.familyName = @"wangg";
    
       [NSKeyedArchiver archiveRootObject:contact toFile:filePath];
}

-(void)unarchive
{
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentFilePath = paths.firstObject;
    NSString *filePath = [documentFilePath stringByAppendingPathComponent:@"fetchContacts"];
    
    CNMutableContact *p1 = [NSKeyedUnarchiver unarchiveObjectWithFile:filePath] ;
    
    NSLog(@"%@", p1.familyName);
    NSLog(@"%@", p1.givenName);
}

- (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;
}

-(NSInteger)getCurrentDay
{
        NSDate *date = [NSDate date];
        NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
        [formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
        //获取当前时间日期展示字符串 如：2019-05-23-13:58:59
    //    NSString *str = [formatter stringFromDate:date];
        NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
        NSDateComponents *comps = [[NSDateComponents alloc] init];
    //    NSInteger unitFlags = NSCalendarUnitYear |NSCalendarUnitMonth |NSCalendarUnitDay |NSCalendarUnitWeekday |NSCalendarUnitHour |NSCalendarUnitMinute |NSCalendarUnitSecond;
        comps = [calendar components:NSCalendarUnitDay fromDate:date];
        NSInteger day = [comps day];
    
    return day;
}

-(NSString *)getNowTimeTimestamp{
    NSDate *datenow = [NSDate date];
    NSString *timeSp = [NSString stringWithFormat:@"%ld", (long)[datenow timeIntervalSince1970]];
    return timeSp;
}

//时间戳变为格式时间
- (NSString *)convertStrToTime:(NSString *)timeStr
{
    long long time=[timeStr longLongValue];
    NSDate *date = [[NSDate alloc]initWithTimeIntervalSince1970:time];
    NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
    [formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSString *timeString=[formatter stringFromDate:date];
    return timeString;
    
//    NSString* timeStr = @"2020-07-08 03:45:31";
//       NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
//       [formatter setDateStyle:NSDateFormatterMediumStyle];
//       [formatter setTimeStyle:NSDateFormatterShortStyle];
//       [formatter setDateFormat:@"YYYY-MM-dd HH:mm:ss"]; // ----------设置你想要的格式,hh与HH的区别:分别表示12小时制,24小时制
//
//       //设置时区,这个对于时间的处理有时很重要
//       //例如你在国内发布信息,用户在国外的另一个时区,你想让用户看到正确的发布时间就得注意时区设置,时间的换算.
//       //例如你发布的时间为2010-01-26 17:40:50,那么在英国爱尔兰那边用户看到的时间应该是多少呢?
//       //他们与我们有7个小时的时差,所以他们那还没到这个时间呢...那就是把未来的事做了1550738762
//
//       NSTimeZone* timeZone = [NSTimeZone timeZoneWithName:@"Asia/Shanghai"];
//       [formatter setTimeZone:timeZone];
//       NSDate* date = [formatter dateFromString:timeStr]; //------------将字符串按formatter转成nsdate
//       NSDate *datenow = [NSDate date];//现在时间,你可以输出来看下是什么格式
//       NSString *nowtimeStr = [formatter stringFromDate:datenow];//----------将nsdate按formatter格式转成
//
//       //时间转时间戳的方法:
//       NSString *timeSp = [NSString stringWithFormat:@"%ld", (long)[date timeIntervalSince1970]];
//       NSLog(@"timeSp:%@",timeSp); //时间戳的值
}



-(void)registerDeleteOrMergeCount
{
    NSString *key = [NSString stringWithFormat:@"%ld",(long)[[ICContactsTool shareInstance] getCurrentDay]];
    NSUbiquitousKeyValueStore *keyValueStore = [NSUbiquitousKeyValueStore defaultStore];
    NSString *count = [keyValueStore objectForKey:[NSString stringWithFormat:@"delete_%@",key]];
    if (count.length == 0) {
        // 设置不完整联系人删除次数
        [keyValueStore setObject:@"5" forKey:[NSString stringWithFormat:@"delete_%@",key]];
        // 设置合并联系人次数
        [keyValueStore setObject:@"5" forKey:[NSString stringWithFormat:@"merge_%@",key]];
        
        [keyValueStore synchronize];
    }
}

-(void)resetCount
{
    NSString *key = [NSString stringWithFormat:@"%ld",(long)[[ICContactsTool shareInstance] getCurrentDay]];
    NSUbiquitousKeyValueStore *keyValueStore = [NSUbiquitousKeyValueStore defaultStore];
    [keyValueStore removeObjectForKey:[NSString stringWithFormat:@"delete_%@",key]];
    [keyValueStore removeObjectForKey:[NSString stringWithFormat:@"merge_%@",key]];
    [keyValueStore synchronize];
}

-(void)enterContactsDetail:(CNContact *)contact controller:(nonnull UIViewController *)controller push:(BOOL)push
{
    self.contactController = controller;
    self.contactPush = push;
    //1.创建Contact对象，必须是可变的
    CNContactViewController *contactController = [CNContactViewController viewControllerForContact:contact.mutableCopy];
    /// 是否显示打电话、发短信等按钮
    contactController.allowsActions = YES;
    /// 能否修改数据
    contactController.allowsEditing = YES;
    /// 是否显示联系人的关联联系人
    contactController.shouldShowLinkedContacts = YES;

    if (self.note.length) {
        unsigned int count = 0;
        Ivar *members = class_copyIvarList([CNContact class], &count);
        for (int i = 0; i < count; i++) {
            Ivar var = members[i];
            const char *memberName = ivar_getName(var);
            NSString *str = [NSString stringWithUTF8String:memberName];
            if ([str isEqualToString:@"_note"]) {
                //    Ivar var = class_getInstanceVariable([CNContact class], "_note");
                object_setIvar(contactController.contact, var, self.note);
                break;
            }
        }
    }
    self.note = @"";

    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];
    if (push) {
        [controller.navigationController pushViewController:contactController animated:YES];
    }else{
        UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController: contactController];
        nav.modalPresentationStyle =  UIModalPresentationFullScreen;
        [controller presentViewController:nav animated:YES completion:nil];
    }

}

- (void)dismissContactController {
    if (self.contactPush) {
        [self.contactController.navigationController popViewControllerAnimated:YES];
    }else{
        [self.contactController.navigationController dismissViewControllerAnimated:YES completion:nil];
    }
}

- (UIViewController *)currentVC{
    UIViewController *result = nil;
    UIWindow * window = [UIApplication sharedApplication].windows.lastObject;
    //app默认windowLevel是UIWindowLevelNormal，如果不是，找到UIWindowLevelNormal的
    if (window.windowLevel != UIWindowLevelNormal)
    {
        NSArray *windows = [[UIApplication sharedApplication] windows];
        for(UIWindow * tmpWin in windows)
        {
            if (tmpWin.windowLevel == UIWindowLevelNormal)
            {
                window = tmpWin;
                break;
            }
        }
    }
    id  nextResponder = nil;
    UIViewController *appRootVC=window.rootViewController;
    //    如果是present上来的appRootVC.presentedViewController 不为nil
    if (appRootVC.presentedViewController) {
        nextResponder = appRootVC.presentedViewController;
    }else{
        if ([window subviews].count > 0) {//防止崩溃
            UIView *frontView = [[window subviews] lastObject];
            nextResponder = [frontView nextResponder]; //  这方法下面有详解    </span>
        }
    }
    
    if ([nextResponder isKindOfClass:[UITabBarController class]]){
        UITabBarController * tabbar = (UITabBarController *)nextResponder;
        UINavigationController * nav = (UINavigationController *)tabbar.viewControllers[tabbar.selectedIndex];
        //        UINavigationController * nav = tabbar.selectedViewController ; 上下两种写法都行
        result=nav.childViewControllers.lastObject;
        
    }else if ([nextResponder isKindOfClass:[UINavigationController class]]){
        UIViewController * nav = (UIViewController *)nextResponder;
        result = nav.childViewControllers.lastObject;
    }else if ([nextResponder isKindOfClass:[UIWindow class]]){
        result = window.rootViewController;
        if ([result isKindOfClass:[UINavigationController class]]){
            UIViewController * nav = (UIViewController *)result;
            result = nav.childViewControllers.lastObject;
        }
    }else{
        result = nextResponder;
    }
    
    return result;
}



@end
