//
//  WMLoginObject.m
//  Gengmei
//
//  Created by Thierry on 2/11/15.
//  Copyright (c) 2015 Wanmeichuangyi. All rights reserved.
//


#import "GMLoginManager.h"
#import "WMNetService.h"
#import "JPUSHService.h"
#import "AppDelegate+ViewControl.h"
#import "GMServerDomains.h"
#import "GMThirdPartyLoginHelper.h"
#import "GMJpushKey.h"

static NSString * userKey = @"userKey";

@interface GMLoginManager()

@property (nonatomic, strong) WMUser *user;

@end
@implementation GMLoginManager

//@synthesize user = _user;

+ (instancetype)shareInstance
{
    static dispatch_once_t onceToken;
    static id instance = nil;
    dispatch_once(&onceToken, ^{
        instance = [[[self class] alloc] init];
    });

    return instance;
}

- (instancetype)init
{
    self = [super init];
    if (self) {

        // user 只可以在这里初始化
        _user = [GMCache fetchObjectAtDocumentPathWithkey:userKey];
        if (!_user) {
            _user = [WMUser new];
        }

        // 如果cookie因为某种原因丢失了，或者用户userId为空，都属于访客模式
        NSArray *cookies = [[NSHTTPCookieStorage sharedHTTPCookieStorage] cookiesForURL:[NSURL URLWithString:APIHOST]];
        if (_user.userId == 0 || cookies.count == 0) {
            _isVisitor = YES;
        }

        // 注册登录失败通知
        [self addObserver];
    }
    return self;
}

- (void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)addObserver{
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(doLogoutAndShowLoginView) name:LOGIN_EXPIRED object:nil];
}

#pragma mark - 登录周期

/**
 *  @brief  显示登录页
 */
- (BOOL)showLoginViewIfNeeded
{
    if ([GMLoginManager shareInstance].isVisitor) {
        
        UIViewController *tabCtrl = AppDelegate.tabBarController;
        if (![tabCtrl isKindOfClass:[GMTabBarController class]]) {
            return YES;
        }
        for (UIViewController *viewCtrl in tabCtrl.childViewControllers) {
            NSLog(@"UIViewController:%@",viewCtrl.childViewControllers);
        }
        [[AppDelegate shareInstance] configGuideRootView];
        
        [[AppDelegate shareInstance] reloadShowRoowView:tabCtrl];
        
        [[AppDelegate shareInstance] showNextRootView];
        
        
        
        /*
        if (![AppDelegate.navigation.visibleViewController isKindOfClass:[ALSignInViewController class]]) {
            ALSignInViewController *controller = [[ALSignInViewController alloc] init];
            controller.isPresent = YES;
            [AppDelegate.navigation pushViewController:controller animated:YES];
        }*/

        return YES;
    }
    return NO;
}

- (void)loginSuccessWithUserInfo:(NSDictionary *)dic shouldBroadcast:(BOOL)broadcast {
    
    
    _isVisitor = NO;
    [self saveUserWithUserInfo:dic];
    
    // 获取用户信息
    [GMSignInManager getUserProfileUserId:self.user.userId finishBlock:^(NSString *message, BOOL success, id data) {
        [[AppDelegate shareInstance] enableShowNextRootView:[ALSignInViewController class]];
    }];
    
    // 全局通知用户登录成功
    if (broadcast) {
        [[NSNotificationCenter defaultCenter] postNotificationName:LOGIN_SUCCESS_NOTIFICATION object:nil];
    }
    
    // 所以逻辑加在这里，这样可以保证极光RegistrationID可以被上传
    [[GMLoginManager shareInstance] appOpenJpushRegistration];

    // 每次重新登录时，要向服务器注册极光 ID
    [[GMLoginManager shareInstance] loginJpushRegistration];

    // 把用户ID映射到Phobos中去
//    [self resetPhobosUserId];
    
//    [AppDelegate.shareInstance loginIMServer];
}

- (void)saveUserWithUserInfo:(NSDictionary *)dic {
    
    WMUser *user = [GMLoginManager shareInstance].user;
    user.userId = [SafeNumber(dic[@"user_id"]) integerValue];
    user.nickName = SafeString(dic[@"nick_name"]);
    user.portrait = SafeString(dic[@"profile_pic"]);
    
    if ([[dic allKeys] containsObject:@"has_answered"]) {
        user.has_answered = [dic[@"has_answered"] boolValue];
    }
    if ([[dic allKeys] containsObject:@"detail_setted"]) {
        user.detail_setted = [dic[@"detail_setted"] boolValue];
    }
    if ([[dic allKeys] containsObject:@"has_scan_face"]) {
        if ([[[NSUserDefaults standardUserDefaults] objectForKey:kShowScanFace] boolValue]) {
            user.has_scanFace = YES;
        } else {
            user.has_scanFace = [dic[@"has_scan_face"] boolValue];
        }
    }
    user.fittingId = SafeString(dic[@"fitting_id"]);
    
    if (![SafeValue(dic[@"age_display"]) isKindOfClass:[NSNull class]]) {
        user.age = SafeString(dic[@"age_display"]);
    }
    if (![SafeValue(dic[@"age"]) isKindOfClass:[NSNull class]]) {
        user.ageCode = SafeString(dic[@"age"]);
    }
    // 保存国家数据
    NSDictionary *country_info = dic[@"country_info"];
    if (country_info && ![SafeValue(country_info) isKindOfClass:[NSNull class]]) {
        
        ALCountryObject *countryObject = [[ALCountryObject alloc] initWithDictionary:country_info error:nil];
        user.language = countryObject.language;
        user.countryName = countryObject.name;
        user.countryId = countryObject.id;
    }
    [self saveUser];
        
}

- (void)loginCancel{
    [[NSNotificationCenter defaultCenter] postNotificationName:LOGIN_CANCEL_NOTIFICATION object:nil];
}

- (void)saveUser {
    
    //user属于用户重要数据，如果存储在沙河cache目录下，当系统内存紧张时候，系统可能会删除user数据，所以必须存储在Document目录下
    [GMCache storeObjectAtDocumentPathWithkey:userKey object:_user block:nil];
}

#pragma mark - 注销操作

- (void)shouldLogout {
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"确定退出此帐号"
                                                                   message:@"提示: 退出之后用户必须重新登录"
                                                            preferredStyle:UIAlertControllerStyleAlert];
    [alert addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:nil]];
    [alert addAction:[UIAlertAction actionWithTitle:@"确定" style:0 handler:^(UIAlertAction * _Nonnull action) {
        [self doLogoutAndShowHomeView];
    }]];
    [AppDelegate.shareInstance.window.rootViewController presentViewController:alert animated:YES completion:nil];
}

- (void)doLogout{
    
    [GMHudModule showLoading:nil];
    __weak __typeof(self)weakSelf = self;
    [GMSignInManager loginOut:^(NSString *message, BOOL success, id data) {
        if (success) {
            [GMHudModule toast:@"退出登录成功"];
            [weakSelf dealLogoutInfo];
        } else {
            [GMHudModule toast:message];
        }
    }];
}

- (void)dealLogoutInfo {
    // 移除 kRegistrationId
    //    [[NSUserDefaults standardUserDefaults] removeObjectForKey:[GMJpushKey registrationId]];
    //    [[NSUserDefaults standardUserDefaults] removeObjectForKey:[GMJpushKey registrationOpenKey]];
    
    // 清空登录状态，清空 user 在内存中的信息
    _isVisitor = YES;
    [self emptyUser];
    
    // 移除当前用户的扫脸标记展示
    [[NSUserDefaults standardUserDefaults] removeObjectForKey:kShowScanFace];
    [[NSUserDefaults standardUserDefaults] synchronize];
    
    // 移除用户信息
    [GMCache removeObjectAtDocumentPathWithkey:userKey block:^(TMDiskCache *cache, NSString *key, id<NSCoding> object, NSURL *fileURL) {
    }];
    
    //删除 cookie
    NSArray *cookies = [[NSHTTPCookieStorage sharedHTTPCookieStorage] cookiesForURL:[NSURL URLWithString:APIHOST]];
    [cookies enumerateObjectsUsingBlock:^(NSHTTPCookie *cookie, NSUInteger idx, BOOL *stop) {
        [[NSHTTPCookieStorage sharedHTTPCookieStorage] deleteCookie:cookie];
    }];
    
    
    [GMThirdPartyLoginHelper thirdPartyLogout];
    
    // 把用户ID从Phobos中去除
    [self resetPhobosUserId];
    
    // 退出登录通知
    [[NSNotificationCenter defaultCenter] postNotificationName:LOGOUT_NOTIFICATION object:nil];
    
    // 断开和极光的IM长连接
    //    [AppDelegate.shareInstance logOutIMServer];
}

- (void)emptyUser {
    
    WMUser *user = [GMLoginManager shareInstance].user;
    user.userId = 0;
    user.nickName = @"";
    user.portrait = @"";
    user.has_answered = YES;// 默认不进入问答
    user.detail_setted = YES;// 默认不进行设置用户信息
    user.has_scanFace = YES;// 默认不进入扫脸入口
    user.fittingId = @"";
    user.age = @"";
    user.ageCode = @"";
    user.language = @"";
    user.countryName = @"";
    user.countryId = @"";
}

/**
 *  @brief  收到403。无论是否为登录状态，直接弹出登录窗口
 */
- (void)doLogoutAndShowLoginView {
    
    [self dealLogoutInfo];
    [[GMLoginManager shareInstance] showLoginViewIfNeeded];
}

- (void)doLogoutAndShowHomeView {
    
    [self doLogout];
    // 重置全部 controller
    UIViewController *viewContrl = AppDelegate.tabBarController;
    if (![viewContrl isKindOfClass:[GMTabBarController class]]) {
        
        [[AppDelegate shareInstance] showHomeView];
        
    } else {
        
        // 加载当前的tabBarController
        [[AppDelegate shareInstance] reloadShowRoowView:viewContrl];
        [[AppDelegate shareInstance] showNextRootView];
        [AppDelegate.tabBarController selectTab:0];
    }
}

#pragma mark - 登录、登出的情况下重置Phobos的userID
- (void)resetPhobosUserId
{
    WMUser *user = [[GMLoginManager shareInstance] user];
    if (user) {
        Phobos *phobos = [Phobos sharedClient];
        [phobos setUserId:user.userId == 0 ? @"" : [NSString stringWithFormat:@"%ld", user.userId]];
    }
}

#pragma mark - 远程推送注册

- (void)jpushRegistration:(NSString *)regStoredKey{
    @try {
        /* 向服务器注册极光ID */
//        NSString *savedRegistrationID = [[NSUserDefaults standardUserDefaults] objectForKey:regStoredKey];
        NSString *registrationID = [JPUSHService registrationID];
        NSString *deviceId = [UIDevice deviceId];
        WMUser *user = [[GMLoginManager shareInstance] user];
        NSDictionary *param;
        
        if ([GMLoginManager shareInstance].isVisitor)
        {
            param = @{
                      @"registration_id":SafeString(registrationID),
                      @"device_id":SafeString(deviceId)
                      };
        }
        else
        {
            param = @{
                      @"registration_id":SafeString(registrationID),
                      @"device_id":SafeString(deviceId),
                      @"user_id":SafeNumber(@(user.userId))
                      };
        }
        // 在 registrationId 为空时，向服务器注册
        //        if (![savedRegistrationID isNonEmpty] && [registrationID isNonEmpty]) {
        [[WMNetService sharedInstance] sendRequestWithURLString:API_JIGUANG_PUSH parameters:param method:HttpMethodPost success:^(NSDictionary *responseObject) {
            if ([responseObject[@"error"] integerValue] == 0) {
                [[NSUserDefaults standardUserDefaults] setObject:registrationID forKey:regStoredKey];
                [[NSUserDefaults standardUserDefaults] synchronize];
            }
        } failed:^(NSString *errorMsg) {
            debugLog(@"%@",errorMsg);
        }];
//        }
    } @catch (NSException *exception) {
        debugLog(@"%@", exception.description);
    }
}

- (void)appOpenJpushRegistration {
    [self jpushRegistration:[GMJpushKey registrationOpenKey]];
}

- (void)loginJpushRegistration {
    [self jpushRegistration:[GMJpushKey registrationId]];
}

#pragma mark - Setter
- (void)setIsVisitor:(BOOL)isVisitor{
    [self willChangeValueForKey:@"isVisitor"];
    _isVisitor = isVisitor;
    [self didChangeValueForKey:@"isVisitor"];
}

@end
