//
//  AppDelegate+AppInit.m
//  Gengmei
//
//  Created by 翟国钧 on 16/3/22.
//  Copyright © 2016年 更美互动信息科技有限公司. All rights reserved.
//

#import "AppDelegate+AppInit.h"
#import "AppDelegate+SDK.h"
#import "AppDelegate+ViewControl.h"

#import "WMCityObject.h"
#import "AppDelegate+SDK.h"
#import <objc/runtime.h>
#import "AFNetworking.h"
#import "GMLocationManager.h"
#import "WMAppConfigObject.h"
#import "GMLaunchManager.h"
#import "GMTabBarIconManager.h"
#import "ALConfigObject.h"
#import "GMSignInManager.h"


@import GMNetworking;
@implementation AppDelegate (AppInit)

- (void)setNetStatusManager:(AFNetworkReachabilityManager *)netStatusManager {
    objc_setAssociatedObject(self, @selector(netStatusManager), netStatusManager, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

- (AFNetworkReachabilityManager *)netStatusManager {
    AFNetworkReachabilityManager *_netStatusManager = objc_getAssociatedObject(self, @selector(netStatusManager));
    if (_netStatusManager) {
        return _netStatusManager;
    } else {
        AFNetworkReachabilityManager *_netStatusManager = [AFNetworkReachabilityManager manager];
        self.netStatusManager = _netStatusManager;
        return _netStatusManager;
    }
}


- (void)setNetWorkStatus:(NSString *)netWorkStatus {
    objc_setAssociatedObject(self, @selector(netWorkStatus), netWorkStatus, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
- (NSString *)netWorkStatus {
    return objc_getAssociatedObject(self, @selector(netWorkStatus));
}


/**
 app/config依赖于定位，所以必须在定位成功后发起
 */
- (void)prepareFetchAppConfig {
    __weak __typeof(self)weakSelf = self;

    // 如果没有开启地理位置，app config也是要请求的
    if ([GMLocationManager hasOpenLocationService]) {
        [[GMLocationManager shareInstance] addBlock:^(CLLocation *location){
            [weakSelf dispatchOnceAppConfig];
        }];
    } else {
        [self dispatchOnceAppConfig];
    }
    
//    [self showHomeView];
    
#warning 开发阶段暂时屏蔽入口跳转
    // 获取用户基本信息
    [self getUserProfileInfo];
}

- (void)dispatchOnceAppConfig {
    // 因为app config只需要走一次，但是location会多次调用回调，所以需要添加一个dispatch_once
    // app启动的配置接口（目前暂时只是做了第三方按钮登陆审核期间隐藏） #5.5.0增加了强制更新的配置
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        [self setupAppConfig];
    });
}

/**
 监听网络状态的改变
 */
- (void)setupNetWorkStatus {
    //目前只区分wifi,非wifi以及没有网络的情况
    [self.netStatusManager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        //网络请求添加的通用参数
        if(status == AFNetworkReachabilityStatusReachableViaWiFi) {
            self.netWorkStatus = @"1";
        } else if(status == AFNetworkReachabilityStatusNotReachable) {
            self.netWorkStatus = @"-1";
        } else {
            self.netWorkStatus = @"0";
        }
        [self setUpNetService];
        [Phobos sharedClient].netStatus = self.netWorkStatus;
        [[NSNotificationCenter defaultCenter] postNotificationName:@"network_connection" object:nil userInfo:@{@"status": @(status)}];
    }];
    [self.netStatusManager startMonitoring];
}


/**
 setupAppConfig 该方法必须在地理位置回调后再调用，否则切换城市功能会不好使。
 */
- (void)setupAppConfig {
    
//    NSString *localPopId = [[[NSUserDefaults standardUserDefaults] objectForKey:kpopupAdId] isNonEmpty] ? [[NSUserDefaults standardUserDefaults] objectForKey:kpopupAdId]:@"";
//    
//    //取出当前版本APP的启动次数,达到30次就弹出求好评窗口
//    NSInteger count = [[NSUserDefaults standardUserDefaults] integerForKey:kAPPLoadTimes];
//    [[NSUserDefaults standardUserDefaults] setInteger:++count forKey:kAPPLoadTimes];
//    [[NSUserDefaults standardUserDefaults] synchronize];
//    NSString *appLoadTimes = [NSString stringWithFormat:@"%zd", count];
//    
//    //取出当前版本APP的启动次数,传给后端,又后端判断更新弹窗
//    NSInteger num = [[GMCache fetchObjectAtDocumentPathWithkey:kAPPStartTimes] integerValue];
//    [GMCache storeObjectAtDocumentPathWithkey:kAPPStartTimes object:@(++num)];
//    NSString *appStartTimes = [NSString stringWithFormat:@"%zd", num];
//    
//    // cityAlert = 0 表示不需要弹alert; 1 告诉服务器此时需要判断用户位置是否需要弹出更改城市的alert。
//    NSString *cityAlert = @"0";
//    
//    // 是否要弹出更改城市的alert还要看上次用户的选择
//    NSDate *alertCityDate = [GMCache fetchObjectAtDocumentPathWithkey:kAlertCityDate];
//    
//    // 因为alertCityDate是已经过去的时间，所以需要取绝对值
//    NSTimeInterval time = fabs([alertCityDate timeIntervalSinceNow]);
    
    // 有city表示不是第一次启动。第一次启动时city为空，也不需要让服务器判断
    // !alertCityDate 表示第一次安装更改城市的alert选择了“是”
    // time > 7 * 3600 * 24 表示存的时间已经超过一周
    
    /** 2018.11.26 zhouLiang注释 */
    /**
     WMCityObject *city = GMCityManager.currentCity;
     // alertCityDate 不存在 或者 time大于7天
     if (city && (!alertCityDate || time > 3 * 3600 * 24)) {
     cityAlert = @"1";
     }
     
     NSDictionary *params = @{@"popup_ad_id":localPopId,
     @"city_alert":cityAlert,
     @"startup":appLoadTimes,
     @"num": appStartTimes,
     @"scale": @([UIScreen mainScreen].scale)
     };
     */
    
    NSMutableURLRequest *request = [[GMNetworking customRequestWithApi:API_CONFIG_TABBAR method:GMHTTPMethodGet parameters:nil] mutableCopy];
    request.timeoutInterval = 30;
    [GMNetworking sendOC:request completion:^(GMResponseOC * _Nonnull response) {
        if (response.isSuccess) {
            NSDictionary *data = response.data;
            
            NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
            [defaults setObject:data forKey:@"phoneAreaKey"];
            [defaults synchronize];
            
            [GMLaunchManager shareManager].appConfigObject = [[WMAppConfigObject alloc] initWithDictionary:data error:nil];
            [GMTabBarIconManager saveTabbarConfig];
            [GMTabBarIconManager downloadTabbarIcons];                        
        } else {
        }
    }];
}

/**
 * 获取备用域名切换信息
 * 备用域名信息获取为单独接口获取
 */
- (void)fetchBackupDominConfig {
    
    __weak __typeof(self)weakSelf = self;
    NSString *hostString = @"http://backend.wanmeizhensuo.com";
#if defined DEBUG
    hostString = @"http://backend.test.env";
#endif
    NSURL *baseURL = [NSURL URLWithString:hostString];
    AFHTTPSessionManager *sessionManager = [[AFHTTPSessionManager alloc] initWithBaseURL:baseURL];
    sessionManager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript", @"text/html", nil];
    [sessionManager GET:API_BACKUP_DOMIN parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSDictionary *data = responseObject[@"data"];
        NSString *backupDomin = [NSString stringWithFormat:@"%@", data[@"domain"]];
        
        if (backupDomin && ![backupDomin isEqualToString:@""] && ![backupDomin hasPrefix:@"http"]) {
            backupDomin = [NSString stringWithFormat:@"http://%@",backupDomin];
        }
        // 域名发生变化的时候进行切换
        if (![backupDomin isEqualToString:@""] && ![backupDomin isEqualToString:APIHOST]) {
            
            // 同步Cookie
            [weakSelf synchronizeCookie:backupDomin];
            
            [[NSUserDefaults standardUserDefaults] setValue:backupDomin forKey:kBackupDomin];
            [[NSUserDefaults standardUserDefaults] synchronize];
            
            // 发送域名切换成功通知
            [[NSNotificationCenter defaultCenter] postNotificationName:APP_DOMIN_CHANGE_SUCCESS
                                                                object:nil userInfo:nil];
            
            // 初始化配置信息
            [weakSelf reloadAppInitConfig];
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
    }];
}

// 初始化配置信息
- (void)reloadAppInitConfig {
    
    // 网络配置初始化应该尽量放在最开始的位置
    [self setUpNetService];
    
    // 域名切换后 如果appConfigObject中仍旧是没有内容的，代表老域名已经废弃，再次进行app/config接口请求
    if (![GMLaunchManager shareManager].appConfigObject) {
        [self setupAppConfig];
    }
    
    // 获取举报原因
    [self fetchReportReason];
}

// 获取用户基本信息
- (void)getUserProfileInfo {
    
    if ([GMLoginManager shareInstance].isVisitor) {
        // 配置启动跟页面
        [self configWindowRootController];
    } else {
        NSInteger userId = [GMLoginManager shareInstance].user.userId;
        [GMSignInManager getUserProfileUserId:userId
                                  finishBlock:^(NSString *message, BOOL success, id data) {
                                      
                                      [GMHudModule hideLoading];
                                      // 配置启动跟页面
                                      [self configWindowRootController];
                                  }];
    }
}

- (void)setupGlobalAppearence {
    [UITextField appearance].tintColor = UIColor.mainVisual;
    [UITextView appearance].tintColor = UIColor.mainVisual;
}

// 下载举报原因
- (void)fetchReportReason {

}

// 同步Cookie
- (void)synchronizeCookie:(NSString *)apiHost {
    NSArray *cookies = [[NSHTTPCookieStorage sharedHTTPCookieStorage] cookiesForURL:[NSURL URLWithString:APIHOST]];
    NSArray *NewCookies = [[NSHTTPCookieStorage sharedHTTPCookieStorage] cookiesForURL:[NSURL URLWithString:apiHost]];
    if (NewCookies.count <= 0) {
        for (NSHTTPCookie *cookie in cookies){
            // cookiesWithResponseHeaderFields方法，需要为URL设置一个cookie为NSDictionary类型的header，注意NSDictionary里面的forKey需要是@"Set-Cookie"
            NSArray *headeringCookie = [NSHTTPCookie cookiesWithResponseHeaderFields:
                                        [NSDictionary dictionaryWithObject:
                                         [[NSString alloc] initWithFormat:@"%@=%@",[cookie name],[cookie value]]
                                                                    forKey:@"Set-Cookie"]
                                                                              forURL:[NSURL URLWithString:apiHost]];
            // 通过setCookies方法，完成设置，这样只要一访问URL为HOST的网页时，会自动附带上设置好的header
            [[NSHTTPCookieStorage sharedHTTPCookieStorage] setCookies:headeringCookie
                                                               forURL:[NSURL URLWithString:apiHost]
                                                      mainDocumentURL:nil];
        }
    }
}

@end
