//
//  Push2Module.m
//  WeexPluginTemp
//
//  Created by  on 17/3/14.
//  Copyright © 2017年 . All rights reserved.
//

#import "Push2Module.h"
#import <WeexPluginLoader/WeexPluginLoader.h>
#import <GTSDK/GeTuiSdk.h>
@interface Push2Module () <GeTuiSdkDelegate>
@end

@implementation Push2Module

WX_PlUGIN_EXPORT_MODULE(push2, Push2Module)
WX_EXPORT_METHOD(@selector(show))

/**
 */
-(void)show
{
    UIAlertView *alertview = [[UIAlertView alloc] initWithTitle:@"title" message:@"module push2 is created sucessfully" delegate:self cancelButtonTitle:@"cancel" otherButtonTitles:@"ok", nil];
    [alertview show];
    
}
-(void)test
{
    NSLog(@"test");
}
- (void)initGeTui:(NSDictionary *)initOptions :(UIResponder *)delegate{
    [GeTuiSdk startSdkWithAppId:initOptions[@"appId"] appKey:initOptions[@"appId"] appSecret:initOptions[@"appId"] delegate:self];
    //[2]:注册APNS
    [self registerRemoteNotification];
    //［2-EXT]: 获取启动时收到的APN数据
}
/** 注册远程通知 */
- (void)registerRemoteNotification {
    
#ifdef __IPHONE_8_0

#else
    UIRemoteNotificationType apn_type = (UIRemoteNotificationType)(UIRemoteNotificationTypeAlert | UIRemoteNotificationTypeSound | UIRemoteNotificationTypeBadge);
    [[UIApplication sharedApplication] registerForRemoteNotificationTypes:apn_type];
#endif
}
#pragma mark 个推注册
/// 唤醒
- (void)application:(UIApplication *)application performFetchWithCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {
    //[5] Background Fetch 恢复SDK 运行
    [GeTuiSdk resume];
    completionHandler(UIBackgroundFetchResultNewData);
}
/// 请求Token
- (void)geTuiApplication:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
    NSString *token = [[deviceToken description] stringByTrimmingCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@"<>"]];
    NSString *strDeviceToken = [token stringByReplacingOccurrencesOfString:@" " withString:@""];
    NSLog(@"deviceToken:%@", strDeviceToken);
    // [3]:向个推服务器注册deviceToken
    [GeTuiSdk registerDeviceToken:strDeviceToken];
    [[NSUserDefaults standardUserDefaults] setObject:strDeviceToken forKey:@"deviceToken"];
    [[NSUserDefaults standardUserDefaults] setObject:[GeTuiSdk clientId] forKey:@"client_id"];
    [[NSUserDefaults standardUserDefaults] synchronize];
}
/// 如果APNS注册失败通知个推服务器
- (void)geTuiApplication:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError*)error {
    //[3-EXT]:如果APNS注册失败，通知个推服务器
    [GeTuiSdk registerDeviceToken:[[NSUserDefaults standardUserDefaults] objectForKey:@"deviceToken"]];
}
#pragma mark 启动GeTui
- (void)startSdkWith:(NSString *)appID appKey:(NSString *)appKey appSecret:(NSString *)appSecret {
    // [1-1]:通过 AppId、 appKey 、appSecret 启动SDK
    [GeTuiSdk startSdkWithAppId:appID appKey:appKey appSecret:appSecret delegate:self];
    // [1-2]:设置是否后台运行开关
    [GeTuiSdk runBackgroundEnable:YES];
    // [1-3]:设置电子围栏功能，开启LBS定位服务 和 是否允许SDK 弹出用户定位请求
    [GeTuiSdk lbsLocationEnable:YES andUserVerify:YES];
}
#pragma mark - APP运行中接收到通知(推送)处理
/** APP已经接收到“远程”通知(推送) - 透传推送消息  */
//- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult result))completionHandler {
//    // [4-EXT]:处理APN
//    completionHandler(UIBackgroundFetchResultNewData);
//}
#pragma mark - GeTuiSdk Delegate


/// ios的话 可以把要跳转的信息写到setpushinfo的payload里面 客户端收到payload之后去解析跳转 也可以把跳转信息放到透传消息里面 客户端收到透传之后解析跳转
-(void)GeTuiSdkDidReceivePayloadData:(NSData *)payloadData andTaskId:(NSString *)taskId andMsgId:(NSString *)msgId andOffLine:(BOOL)offLine fromGtAppId:(NSString *)appId {
    NSDictionary *msgDict = [NSJSONSerialization JSONObjectWithData:payloadData options:NSJSONReadingAllowFragments error:nil];
    
}

/// SDK收到sendMessage消息回调
- (void)GeTuiSdkDidSendMessage:(NSString *)messageId result:(int)result {
    // [4-EXT]:发送上行消息结果反馈
    // NSString *record = [NSString stringWithFormat:@"Received sendmessage:%@ result:%d", messageId, result];
}
/// SDK遇到错误回调
- (void)GeTuiSdkDidOccurError:(NSError *)error {
    // [EXT]:个推错误报告，集成步骤发生的任何错误都在这里通知，如果集成后，无法正常收到消息，查看这里的通知。
    NSLog(@"个推错误返回%ld %@",(long)error.code,error.localizedDescription);
}
/// SDK运行状态通知
- (void)GeTuiSDkDidNotifySdkState:(SdkStatus)aStatus {
    NSLog(@"%d status 1 启动 2 停止",aStatus);
}
#pragma mark - 私有方法
- (NSString *)formateTime:(NSDate *)date {
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"HH:mm:ss"];
    NSString *dateTime = [formatter stringFromDate:date];
    return dateTime;
}
// 发送本地推送
// 发送本地推送
- (void)showNotificationWithMessage:(NSDictionary *)msgDict {
    UILocalNotification *notification = [[UILocalNotification alloc] init];
    // 设置通知的提醒时间
    notification.timeZone = [NSTimeZone localTimeZone]; // 使用本地时区
    notification.fireDate = [NSDate date];
    
    NSMutableDictionary *userInfo = [[NSMutableDictionary alloc] initWithDictionary:msgDict];
    notification.userInfo = userInfo;
    // 设置提醒的文字内容
    notification.alertBody   = msgDict[@"content"];
    if (!notification.alertBody) {
        notification.alertBody = @"新消息";
    }
    // 8.2以后才有alertTitle
    if ([UIDevice currentDevice].systemVersion.floatValue >= 8.2f) {
        notification.alertTitle = msgDict[@"title"] ? msgDict[@"title"] : @"爱介护";
    }
    notification.soundName= UILocalNotificationDefaultSoundName;
    // 将通知添加到系统中
    [[UIApplication sharedApplication] scheduleLocalNotification:notification];
}

@end
