//
//  NotificationService.m
//  notice
//
//  Created by 张丰 on 2023/7/13.
//  Copyright © 2023 DCloud. All rights reserved.
//

#import "NotificationService.h"
#import <AVFoundation/AVFoundation.h>
#import <UIKit/UIKit.h>
@interface NotificationService ()

@property (nonatomic, strong) void (^contentHandler)(UNNotificationContent *contentToDeliver);
@property (nonatomic, strong) UNMutableNotificationContent *bestAttemptContent;
@property (nonatomic,assign) NSInteger count;
@end

@implementation NotificationService

- (void)didReceiveNotificationRequest:(UNNotificationRequest *)request withContentHandler:(void (^)(UNNotificationContent * _Nonnull))contentHandler {
    self.contentHandler = contentHandler;
    self.bestAttemptContent = [request.content mutableCopy];

    if([self isMediaPush]) {
        // Modify the notification content here...
        self.bestAttemptContent.sound = [UNNotificationSound soundNamed:@"xiaomi.mp3"];
        [self vibrationTimerActon];
    }
    self.contentHandler(self.bestAttemptContent);
}
//收到推送消息后，会先执行此方法
- (void)vibrationTimerActon {
    self.count ++;
    if(self.count > 8) {
        self.count = 0;
        return;
    }
    dispatch_time_t time = dispatch_time(DISPATCH_TIME_NOW, (ino64_t)(1 * NSEC_PER_SEC));
    dispatch_after(time, dispatch_get_main_queue(), ^{
        AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);
        //此处SuiteName要与创建App Groups勾选的一致
        NSUserDefaults *shareDefaults = [[NSUserDefaults alloc] initWithSuiteName:@"group.com.xf.template"];
        NSString *isBackground = [shareDefaults objectForKey:@"isBackground"];
        if([isBackground isEqualToString:@"1"]) {
            [self vibrationTimerActon];
        }
    });
    
}
- (BOOL)isMediaPush {
    
    NSDictionary *push_data = self.bestAttemptContent.userInfo;
    NSString *jsonString = push_data[@"appData"];
    if(jsonString == nil) {
        return false;
    }
    NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
    NSError *error;
    NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:&error];
    if(dict == nil) {
        return false;
    }
    
    NSInteger mediaType = [dict[@"mediaType"] integerValue];
    if(mediaType == 1 || mediaType == 2) {
        return true;
    } else {
        return false;
    }
}
- (void)serviceExtensionTimeWillExpire {
    // Called just before the extension will be terminated by the system.
    // Use this as an opportunity to deliver your "best attempt" at modified content, otherwise the original push payload will be used.
    self.contentHandler(self.bestAttemptContent);
}

@end
