//
//  LoginStateManager.m
//  AIIM
//
//  Created by qitewei on 2025/6/15.
//

#import "LoginStateManager.h"

#import "GLoginController.h"

#import "UserNetApi.h"


#import "UDManager.h"
#import "APPLocker.h"
#import "GWebSocket.h"

@implementation LoginStateManager
+ (instancetype)sharedManager {
    static LoginStateManager *instance = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        instance = [[LoginStateManager alloc] init];
        [instance loadLoginStatusFromStorage];
    });
    return instance;
}

- (instancetype)init {
    self = [super init];
    if (self) {
        // 初始化时自动加载存储的登录状态
        _loggedIn = NO;
    }
    return self;
}

#pragma mark - 登录登出方法

- (void)loginWithAccountInfo:(NSDictionary *)info{
    NSLog(@"version:%@",info[@"version"]);
    [UserNetApi login:info succ:^(int code, NSDictionary * res) {
        NSLog(@"%@",res);
        NSString *codes = res[@"code"];
        if(codes.intValue!=200){
//            [AppAlter showAlertWithContent:res[@"msg"] cancelTitle:@"取消" cancelBlock:nil];
//            [AlertHelper showAlertWithTitle:@"" message:res[@"msg"] cancelButtonTitle:NSLocalizedString(@"Common_cancel", @"") confirmButtonTitle:nil completion:nil];
            return;
        }
        NSString *token =res[@"token"];
        if(token){
            [UDManager.shareInstance setSDManager:res[@"token"] key:gkeytoken];
            [UDManager.shareInstance setSDManager:info[@"username"] key:dkuserloginId];
            [self getUserInfo];
        }
    } fail:^(NSError * _Nonnull error) {
        NSLog(@"--%@",error);
    }];
}

- (void)getUserInfo{
    NSString *token = [UDManager.shareInstance getSDManager:gkeytoken];
    NSLog(@"getUserinfo:%@",token);
    if([token isKindOfClass:[NSString class]]&&token.length>10){
        [UserNetApi getUserinfo:^(int code, NSDictionary * res) {
            //NSLog(@"%@", res[@"code"]);
            NSNumber *gcode=res[@"code"];
            NSDictionary *data=res[@"data"];
           // NSLog(@"%@", data);
            if([gcode intValue]!=200){
                NSLog(@"%@",res[@"msg"]);
                [self clearLoginStatus];
                return;
            }
            NSDictionary *ps = @{@"avatar": data[@"avatar"]?:@"",
                                 @"deptId": data[@"deptId"]?:@"",
                                 //@"domainId":data[@"domainId"],
                                 @"email":data[@"email"]?:@"",
                                 @"id":data[@"id"]?:@"",
                                 @"mobile":data[@"mobile"]?:@"",
                                 @"name":data[@"name"]?:@"",
                                 //@"platformType":data[@"platformType"]?:@"",
                                 //@"registrationId":data[@"registrationId"]?:@"",
                                 @"sex":data[@"sex"]?:@"",
                                 //@"tgbotAdmin":data[@"tgbotAdmin"],
                                 //@"tgbotName":data[@"tgbotName"],
                                 //@"tgbotTk":data[@"tgbotTk"]?:@"",
                                 @"username":data[@"username"]?:@"",
                                 //@"uuid":data[@"uuid"],
                                 //@"voipTk":data[@"voipTk"]?:@""
                                };
            if(code==200){
                self->_loggedIn = YES;
                [UDManager.shareInstance setDDManager:ps key:dkuserinfo];
                [UDManager.shareInstance setSDManager:ps[@"id"] key:dkuserId];
                !self.checkLoginState ?: self.checkLoginState(YES);
            }
        } fail:^(NSError * _Nonnull error) {
            NSLog(@"%@", error);
//            self->_loggedIn = NO;
//            [self clearLoginStatus];
//            !self.checkLoginState ?: self.checkLoginState(NO);
        }];
    }
    else{
        self->_loggedIn = NO;
        [self clearLoginStatus];
        [self showLoginViewController];
//        !self.checkLoginState ?: self.checkLoginState(NO);
    }
}

- (void)logout {
    // 这里应该是实际的登出网络请求
    [UserNetApi logout:nil succ:^(int code, NSDictionary * res) {
        [self logoutSet];
//        [self showLoginViewController];
    } fail:^(NSError * _Nonnull error) {
        NSLog(@"");
    }];
}

- (void)logoutSet{
    [[GWebSocket shareInstance] closeWebSocket];
    [UDManager.shareInstance removeUDManager:gkeytoken];
    [UDManager.shareInstance removeUDManager:dkuserloginId];
    [UDManager.shareInstance removeUDManager:dkuserinfo];
    [APPLocker.sharedLocker removePasswordWithError:nil];
    [self clearLoginStatus];
    self->_loggedIn = NO;
}

#pragma mark - 辅助方法

- (BOOL)checkLoginStatus {
    if (!self.isLoggedIn) {
        // 这里可以弹出登录界面
        [self showLoginViewController];
        return NO;
    }
    return YES;
}

#pragma mark - 本地存储管理

- (void)saveLoginStatusToStorage {
    
}

- (void)loadLoginStatusFromStorage {
    
}

- (void)clearLoginStatus {
    [UDManager.shareInstance removeUDManager:gkeytoken];
    NSString *voiptoken = [UDManager.shareInstance getSDManager:dkvoiptoken];
    [self showLoginViewController];
    NSLog(@"voiptoken:%@",voiptoken);
    if([voiptoken isKindOfClass:[NSString class]]&&voiptoken.length>10){
        NSDictionary *dic = @{
            @"voipTk":voiptoken
        };
        [UserNetApi clearVoipTk:dic succ:^(int code, NSDictionary * res) {
            NSLog(@"clearVoipTk:%@",res);
        } fail:^(NSError * _Nonnull error) {
            
        }];
    }
    
    NSString *pushtoken = [UDManager.shareInstance getSDManager:dkpushtoken];
    NSLog(@"voiptoken:%@",pushtoken);
    if([pushtoken isKindOfClass:[NSString class]]&&pushtoken.length>10){
        NSDictionary *dic = @{
            @"registrationId":pushtoken
        };
        [UserNetApi clearRegistrationId:dic succ:^(int code, NSDictionary * res) {
            NSLog(@"clearRegistrationId:%@",res);
        } fail:^(NSError * _Nonnull error) {
            
        }];
    }
}

#pragma mark - 私有方法

- (void)showLoginViewController {
    // 这里实现弹出登录界面的逻辑
    NSLog(@"需要显示登录界面");
    UIStoryboard *board = [UIStoryboard storyboardWithName:@"Main" bundle:[NSBundle mainBundle]];
    GLoginController *login = [board instantiateViewControllerWithIdentifier:@"LoginController"];
    UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:login];
    [UIApplication sharedApplication].delegate.window.rootViewController = nav;
}

@end
