//
//  AppDelegate+SDK.m
//  GMAlpha
//
//  Created by Q14 on 2018/11/8.
//  Copyright © 2018年 Gengmei. All rights reserved.
//

#import "AppDelegate+SDK.h"
#import "GMCookieManager.h"
#import "AppDelegate+AppInit.h"
#import "GMKey.h"
#import "sys/utsname.h"
#import <AdSupport/AdSupport.h>
#import "GMLocationManager.h"
#import "WMUser.h"
#import "WMCityObject.h"
#import "Alpha-Swift.h"
#import "GMThirdPartyOauthManager.h"
#import <Bugly/Bugly.h>

@import IQKeyboardManager;
@import GMBase;
@import AvoidCrash;
@import Bugly;
@implementation AppDelegate (SDK)
- (void)setupSDKs {
    
    // 注册QQ 微信
    [self setupThirdPartySDK];
    [self setupBugly];
    [self setupPhobos];
}

- (void)setupBugly {
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updateBuglyUserInfo) name:LOGIN_SUCCESS_NOTIFICATION object:nil];
    BuglyConfig *config = [BuglyConfig new];
    config.channel = APP_DISTRIBUTE_CHANNEL;
    config.unexpectedTerminatingDetectionEnable = NO;
    config.reportLogLevel = BuglyLogLevelWarn;
    config.blockMonitorEnable = YES;
    config.blockMonitorTimeout = 2.5;
    [Bugly startWithAppId:BuglyAppID config:config];
    [self updateBuglyUserInfo];
}

- (void)updateBuglyUserInfo {
    WMUser *user = [GMLoginManager shareInstance].user;
    if (user.userId > 0) {
        [Bugly setUserIdentifier:user.nickName ?:@""];
        [Bugly setUserValue:[@(user.userId) stringValue] forKey:@"userId"];
    } else {
        [Bugly setUserIdentifier:@"未登录用户"];
    }
    
    [Bugly setUserValue:APIHOST forKey:@"API_HOST"];
    [Bugly setUserValue:GMCityManager.currentCity.id forKey:@"city"];
    [Bugly setUserValue:@(GMCityManager.isCitySet).stringValue forKey:@"isCitySet"];
    [Bugly setUserValue:SafeString([UIDevice deviceId]) forKey:@"device_id"];
}

- (void)setupPhobos{
    @try {
        Phobos *client = [Phobos clientWithAppName:@"alpha" channelId:APP_DISTRIBUTE_CHANNEL];
#ifdef APPSTORE
        NSString *url = @"https://log.gmeiapp.com/log/collect";
#else
        NSString *url = @"http://log.test.igengmei.com/log/collect";
        
        [client setLogEnabled:NO]; // 调试打Log模式，看情况开启
#endif
        client.serverAPI = url;
        // 传入用户ID
        WMUser *user = [[GMLoginManager shareInstance] user];
        if (user) {
            client.userId = user.userId == 0 ? @"" : [NSString stringWithFormat:@"%ld", user.userId];
        }
        
        WMCityObject *city = GMCityManager.currentCity;
        if (city) {
            [client setCurrentCityId:city.id];
        }
        
        [Phobos setSharedClient:client];
        [Phobos sharedClient].captureNullExpection = ^(NSString *eventId, NSDictionary *dic){
            
        };
        [Phobos sharedClient].getTopController = ^UIViewController *{
            return AppDelegate.visibleController;
        };
    }
    @catch (NSException *exception) {
        debugLog(@"%@",exception.reason);
    }
}
#pragma mark - 防crash
- (void)setupAvoidCrash {
    //启动防止崩溃功能(注意区分becomeEffective和makeAllEffective的区别)
    //具体区别请看 AvoidCrash.h中的描述
    //建议在didFinishLaunchingWithOptions最初始位置调用 上面的方法
    
    [AvoidCrash makeAllEffective];
    
    //若出现unrecognized selector sent to instance导致的崩溃并且控制台输出:
    //-[__NSCFConstantString initWithName:age:height:weight:]: unrecognized selector sent to instance
    //你可以将@"__NSCFConstantString"添加到如下数组中，当然，你也可以将它的父类添加到下面数组中
    //比如，对于部分字符串，继承关系如下
    //__NSCFConstantString --> __NSCFString --> NSMutableString --> NSString
    //你可以将上面四个类随意一个添加到下面的数组中，建议直接填入 NSString
    NSArray *noneSelClassStrings = @[
                                     @"NSNull",
                                     @"NSNumber",
                                     @"NSString",
                                     @"NSDictionary",
                                     @"NSArray"
                                     ];
    [AvoidCrash setupNoneSelClassStringsArr:noneSelClassStrings];
    //监听通知 AvoidCrashNotification, 获取AvoidCrash捕获的崩溃日志的详细信息
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(dealwithCrashMessage:) name:AvoidCrashNotification object:nil];
}

- (void)setupThirdPartySDK{
    [WeiboSDK enableDebugMode:YES];
    [WeiboSDK registerApp:SINAWEIBO_APPID];
    [GMThirdPartyOauthManager shareInstance].tencentOAuth = [[TencentOAuth alloc] initWithAppId:QQ_APPID andDelegate:[GMThirdPartyOauthManager shareInstance]];
    [WXApi registerApp:WEIXIN_APPID enableMTA:YES];
    //向微信注册支持的文件类型
    UInt64 typeFlag = MMAPP_SUPPORT_TEXT | MMAPP_SUPPORT_PICTURE | MMAPP_SUPPORT_LOCATION | MMAPP_SUPPORT_VIDEO |MMAPP_SUPPORT_AUDIO | MMAPP_SUPPORT_WEBPAGE | MMAPP_SUPPORT_DOC | MMAPP_SUPPORT_DOCX | MMAPP_SUPPORT_PPT | MMAPP_SUPPORT_PPTX | MMAPP_SUPPORT_XLS | MMAPP_SUPPORT_XLSX | MMAPP_SUPPORT_PDF;
    [WXApi registerAppSupportContentFlag:typeFlag];
}

- (void)setUpNetService {
    WMNetService *service = [WMNetService sharedInstance];
    service.networking.requestSerializer.HTTPShouldHandleCookies = YES;
    service.apiHost = APIHOST;
    service.apiSecurityHost = [APIHOST stringByReplacingOccurrencesOfString:@"http" withString:@"https" options:NSLiteralSearch range:NSMakeRange(0, 4)];
    service.loginExpiredName = LOGIN_EXPIRED;
    service.urlCommonParameters = [self urlCommonParameters];
    service.handleResponse = ^(NSDictionary *dict){
        [self responseInterceptionWithDict:dict];
    };
    
    __weak __typeof(service)weakService = service;
    //每次get接口请求实时将access_token的写入cookie中
    service.beforeAction = ^{
        NSDictionary *requestHeaderFields = [GMCookieManager requestHeaderFields];
        [weakService.networking.requestSerializer setValue:requestHeaderFields[@"Cookie"] forHTTPHeaderField:@"Cookie"];
    };
    
    //每次上传实时将access_token的写入cookie中
    service.beforeUploadAction = ^ {
        NSDictionary *httpHeader = [GMCookieManager requestHeaderFields];
        return httpHeader;
    };

    
    //swift的网络库初始化
    [self setupNetworking];
    //监控网络状态
    AFNetworkReachabilityManager *manager = [AFNetworkReachabilityManager sharedManager];
    [manager startMonitoring];
}

/**
 *  @author zhaiguojun, 16-03-22
 *
 *  @brief 外部可能会重新获取地理位置，而由于使用两个 GMLocationManager，可能会导致Appdelegate里的经纬度不是同步的，导致接口参数不正确，所以开放一个坐标属性
 *  @since 5.9.2
 */
- (NSString *)urlCommonParameters {
    
#if defined DEBUG
    int dist = 0;
#else
    int dist = 1;
#endif
    
    NSString *latitude = @([GMLocationManager shareInstance].location.coordinate.latitude).stringValue;
    NSString *longitude = @([GMLocationManager shareInstance].location.coordinate.longitude).stringValue;
#if defined DEBUG
    // 测试数据首尔，需要将useTestLocationShouer手动打开
//    if (GMHomeLocationManager.useTestLocationShouer) {
//        latitude = GMHomeLocationManager.latitude_shouer;
//        longitude = GMHomeLocationManager.longitude_shouer;
//    }
#endif
    
    NSString *deviceDetailModel = [UIDevice deviceVersion];//@"iPhone X";
    NSString *deviceId = [UIDevice deviceId];
    
#if defined DEBUG
    // 直接在Setting Bundle中改设备尾号
    NSString *lastNum = [[NSUserDefaults standardUserDefaults] objectForKey:@"device_id"];
    if ([lastNum isNonEmpty]) {
        deviceId = [deviceId stringByReplacingCharactersInRange:NSMakeRange(deviceId.length - 1, 1) withString:lastNum];
    }
#elif defined RELEASE
    NSString *lastNum = [[NSUserDefaults standardUserDefaults] objectForKey:@"device_id"];
    if ([lastNum isNonEmpty]) {
        deviceId = [deviceId stringByReplacingCharactersInRange:NSMakeRange(deviceId.length - 1, 1) withString:lastNum];
    }
#endif
    
    // platform: iPad, iPhone, android
    // deviceDetailModel:目前只支持到6s，和6splus
    return [[NSString stringWithFormat:@"?platform=%@&os_version=%@&version=%@&model=%@&release=%d&idfa=%@&idfv=%@&device_id=%@&channel=%@&app_name=gengmeiios&current_city_id=%@&lat=%@&lng=%@&is_WiFi=%@&phone_id=%@",
             PLATFORM,
             [[UIDevice currentDevice] systemVersion],
             APP_VERSION,
             deviceDetailModel,
             dist ,
             [[[ASIdentifierManager sharedManager] advertisingIdentifier] UUIDString],
             [[[UIDevice currentDevice] identifierForVendor] UUIDString],
             deviceId,
             APP_DISTRIBUTE_CHANNEL,
             GMCityManager.currentCity.id,
             latitude,
             longitude,
             self.netWorkStatus,
             UIDevice.platform
             ]
            stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
}

- (void)registerNetserviceLocationCallbacks {
    [[GMLocationManager shareInstance] addBlock:^(CLLocation *location){
        [self updateLocationCallback:location];
    }];
}

- (void)updateLocationCallback:(CLLocation *)location {
    [WMNetService sharedInstance].urlCommonParameters = [self urlCommonParameters];
    GMNetworking.urlCommonParameters = [self urlCommonParameters];
    [Phobos sharedClient].gps = location;
}

- (void)setupIQKeyboard {
    [IQKeyboardManager sharedManager].enableAutoToolbar = NO;
    NSArray *classes = @[];
    [[IQKeyboardManager sharedManager].disabledDistanceHandlingClasses addObjectsFromArray:classes];
}
#pragma mark - 崩溃通知方法
- (void)dealwithCrashMessage:(NSNotification *)notification {
    //注意:所有的信息都在userInfo中
    //异常拦截并且通过bugly上报
    NSDictionary *info = notification.userInfo;
    /**
     ErrorReason:       导致崩溃的原因
     ErrorPlace:        导致崩溃代码所在地方
     DefaultToDo:       AvoidCrash默认做了什么处理来防止崩溃
     ErrorName:         崩溃名称
     callStackSymbols:  调用栈信息
     */
//    NSArray *callStack = info[@"callStackSymbols"];
//    NSDictionary *extraInfo = @{@"errorPlace" : SafeValue(info[@"errorPlace"]),
//                                @"defaultToDo" : SafeValue(info[@"defaultToDo"])
//                                };
    /**
     *    @brief 上报自定义错误
     *
     *    @param category    类型(Cocoa=3,CSharp=4,JS=5,Lua=6)
     *    @param aName       名称
     *    @param aReason     错误原因
     *    @param aStackArray 堆栈
     *    @param info        附加数据
     *    @param terminate   上报后是否退出应用进程
     */
//    [Bugly reportExceptionWithCategory:3 name:info[@"errorName"] reason:info[@"errorReason"] callStack:callStack extraInfo:extraInfo terminateApp:NO];
}
@end
