//
//  UmPush.m
//  JZPlus_RN
//
//  Created by 丁乐 on 2020/6/6.
//

#import "UmPush.h"
#import <UMPush/UMessage.h>

@interface UmPush ()<UNUserNotificationCenterDelegate>

@end

@implementation UmPush

RCT_EXPORT_MODULE();

-(NSArray<NSString *> *)supportedEvents{
  return @[@"foregroundNotification",@"backstageNotification"];
}

- (dispatch_queue_t)methodQueue{
  return dispatch_get_main_queue();
}


/// 普通注册通知
RCT_EXPORT_METHOD(plainRegister:(RCTPromiseResolveBlock)success
rejecter:(RCTPromiseRejectBlock)reject){
  // Push组件基本功能配置
  UMessageRegisterEntity * entity = [[UMessageRegisterEntity alloc] init];
  //type是对推送的几个参数的选择，可以选择一个或者多个。默认是三个全部打开，即：声音，弹窗，角标
  entity.types = UMessageAuthorizationOptionBadge|UMessageAuthorizationOptionSound|UMessageAuthorizationOptionAlert;
  [UNUserNotificationCenter currentNotificationCenter].delegate=self;
  [UMessage registerForRemoteNotificationsWithLaunchOptions:nil Entity:entity completionHandler:^(BOOL granted, NSError * _Nullable error) {
    if (error) {
      reject(@"错误",@"错误",error);
    }else{
      success(@(granted));
    }
  }];
}


/// 快捷交互 注册通知
/// @param categories 注册事件数据
RCT_EXPORT_METHOD(actionRegister:(NSArray *)categories success:(RCTPromiseResolveBlock)success rejecter:(RCTPromiseRejectBlock)reject){
  
  // Push功能配置
  UMessageRegisterEntity * entity = [[UMessageRegisterEntity alloc] init];
  entity.types = UMessageAuthorizationOptionBadge|UMessageAuthorizationOptionAlert|UMessageAuthorizationOptionSound;
  
  //如果要在iOS10显示交互式的通知，必须注意实现以下代码
  NSMutableSet *UNCategories = [NSMutableSet set];
  
  //  添加交互
  for (int i = 0; i < categories.count; i++) {
    NSDictionary *category = categories[i];
    NSString *categoryId = category[@"categoryId"];
    
    NSArray *actions = category[@"actions"];
    NSMutableArray *UNActions = [NSMutableArray array];
    for (int j = 0; j < actions.count; j++) {
      NSDictionary *action = actions[j];
      NSString * actionId = action[@"actionId"];
      NSString * actionTitle = action[@"actionTitle"];
      UNNotificationAction * UNAction = [UNNotificationAction actionWithIdentifier:actionId title:actionTitle options:UNNotificationActionOptionForeground];
      [UNActions addObject:UNAction];
    }
    
    UNNotificationCategory *UNCategory = [UNNotificationCategory categoryWithIdentifier:categoryId actions:UNActions  intentIdentifiers:@[] options:UNNotificationCategoryOptionCustomDismissAction];
    [UNCategories addObject:UNCategory];
  }
  
  entity.categories = UNCategories;
  
  [UNUserNotificationCenter currentNotificationCenter].delegate=self;
    [UMessage registerForRemoteNotificationsWithLaunchOptions:nil Entity:entity completionHandler:^(BOOL granted, NSError * _Nullable error) {
    if (error) {
      reject(@"错误",@"错误",error);
    }else{
      success(@(granted));
    }
  }];
}


/// iOS10新增：处理前台收到通知的代理方法
/// @param center 通知中心
/// @param notification 通知
/// @param completionHandler 回调
-(void)userNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions))completionHandler{
  
  NSDictionary * userInfo = notification.request.content.userInfo;
  if([notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
      [UMessage setAutoAlert:NO];
      //应用处于前台时的远程推送接受
    [self sendEventWithName:@"foregroundNotification" body:userInfo];
      //必须加这句代码
      [UMessage didReceiveRemoteNotification:userInfo];
  }else{
      //应用处于前台时的本地推送接受
    [self sendEventWithName:@"foregroundNotification" body:userInfo];
  }
  completionHandler(UNNotificationPresentationOptionSound|UNNotificationPresentationOptionBadge|UNNotificationPresentationOptionAlert);
}


/// iOS10新增：处理后台点击通知的代理方法
/// @param center 通知中心
/// @param response 通知
/// @param completionHandler 回调
-(void)userNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)(void))completionHandler{
  
  NSMutableDictionary * userInfo = [NSMutableDictionary dictionaryWithDictionary:response.notification.request.content.userInfo] ;
  
  [userInfo setValue:response.actionIdentifier forKey:@"actionIdentifier"];
  if([response.notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
    //应用处于后台时的远程推送接受
    //必须加这句代码
    [UMessage didReceiveRemoteNotification:userInfo];
    [self sendEventWithName:@"backstageNotification" body:userInfo];
    
  }else{
    //应用处于后台时的本地推送接受
    [self sendEventWithName:@"backstageNotification" body:userInfo];
  }
}


/// 设置是否允许SDK当应用在前台运行收到Push时弹出Alert框（默认开启）
/// @param value 是否开启弹出框
RCT_EXPORT_METHOD(setAutoAlert:(BOOL)value)
{
  [UMessage setAutoAlert:value];
}


/// 获取所有标签
RCT_EXPORT_METHOD(getTags:(RCTPromiseResolveBlock)success
rejecter:(RCTPromiseRejectBlock)reject)
{
  [UMessage getTags:^(NSSet * _Nonnull responseTags, NSInteger remain, NSError * _Nullable error) {
    if(error){
      reject(@"失败",@"失败",error);
    }else{
      success([responseTags allObjects]);
    }
  }];
}


/// 添加标签
/// @param tag 便签字符串
RCT_EXPORT_METHOD(addTags:(NSString *)tag success:(RCTPromiseResolveBlock)success
rejecter:(RCTPromiseRejectBlock)reject)
{
  [UMessage addTags:tag response:^(id  _Nullable responseObject, NSInteger remain, NSError * _Nullable error) {
    if(error){
      reject(@"失败",@"失败",error);
    }else{
      success(responseObject);
    }
  }];
}

/// 移除标签
/// @param tag 便签字符串
RCT_EXPORT_METHOD(deleteTags:(NSString *)tag success:(RCTPromiseResolveBlock)success
rejecter:(RCTPromiseRejectBlock)reject)
{
  [UMessage deleteTags:tag response:^(id  _Nullable responseObject, NSInteger remain, NSError * _Nullable error) {
    if(error){
      reject(@"失败",@"失败",error);
    }else{
      success(responseObject);
    }
  }];
}









@end
