//
//  AppLockPasswordController.m
//  AIIM
//
//  Created by qitewei on 2025/5/7.
//

#import "AppLockPasswordController.h"
#import "APPLocker.h"
#import "GDBManager.h"
#import "UserNetApi.h"
#import "GWebSocket.h"

@interface AppLockPasswordController ()
@property (nonatomic, strong) UITextField *oldPasswordField;  // 旧密码输入框（仅修改密码模式）
@property (nonatomic, strong) UITextField *passwordField;
@property (nonatomic, strong) UITextField *confirmField;
@property (nonatomic, strong) UILabel *titleLabel;
@property (nonatomic, strong) UILabel *messageLabel;
@property (nonatomic, strong) UIButton *submitButton;
@property (nonatomic, strong) UIButton *cancelButton;

@end

@implementation AppLockPasswordController
- (instancetype)initWithChangePasswordMode {
    self = [super init];
    if (self) {
        self.mode = LockViewModeChange;
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // 创建一个点击手势
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(dismissKeyboard)];
    // 将手势添加到主视图上
    [self.view addGestureRecognizer:tap];
    [self configUI];
    [self updateUIForMode];
}
-(void)dismissKeyboard{
    NSLog(@"dismissKeyboard");
    [self.view endEditing:YES];
}
#pragma mark UI
- (void)configUI{
//    [self setNavigationTitle:@"应用锁密码"];
    // 设置导航栏背景色
//    [self setNavigationBarTransparent:YES];
    [self setNavigationBarBackgroundColor:UIColor.clearColor];
    
    // 设置标题颜色和字体
    [self setNavigationTitleColor:[UIColor whiteColor] font:[UIFont boldSystemFontOfSize:16]];
    
    // 设置返回按钮
    [self setBackButtonTitle:@""];
    [self setBackButtonColor:[UIColor whiteColor]];

    UIImageView * bgImageView = [[UIImageView alloc] initWithImage:kImageMake(@"loginBG")];
    [self.view addSubview:bgImageView];
    [bgImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.top.bottom.mas_equalTo(0);
    }];
    
    // 标题
    self.titleLabel = [[UILabel alloc] init];
    self.titleLabel.font = SYSBFONT(20);
    self.titleLabel.textColor = UIColor.whiteColor;
    self.titleLabel.textAlignment = NSTextAlignmentCenter;
    
    [self.view addSubview:self.titleLabel];
    
    // 消息标签
    self.messageLabel = [[UILabel alloc] init];
    self.messageLabel.font = [UIFont systemFontOfSize:14];
    self.messageLabel.textColor = [UIColor redColor];
    self.messageLabel.textAlignment = NSTextAlignmentCenter;
    self.messageLabel.numberOfLines = 0;
    [self.view addSubview:self.messageLabel];
    
    // 旧密码输入框（仅修改密码模式显示）
    self.oldPasswordField = [[UITextField alloc] init];
    self.oldPasswordField.placeholder = NSLocalizedString(@"AppLock_oldPwd_placeholder", @"");
    self.oldPasswordField.secureTextEntry = YES;
    self.oldPasswordField.borderStyle = UITextBorderStyleRoundedRect;
    [self.view addSubview:self.oldPasswordField];
    
    // 密码输入框
    self.passwordField = [[UITextField alloc] init];
    self.passwordField.placeholder = NSLocalizedString(@"login-passw-note", @"");
    self.passwordField.secureTextEntry = YES;
    self.passwordField.borderStyle = UITextBorderStyleRoundedRect;
    [self.view addSubview:self.passwordField];
    
    // 确认密码输入框 (仅在设置和修改模式显示)
    self.confirmField = [[UITextField alloc] init];
    self.confirmField.placeholder = NSLocalizedString(@"AppLock_secondPwd_placeholder", @"");
    self.confirmField.secureTextEntry = YES;
    self.confirmField.borderStyle = UITextBorderStyleRoundedRect;
    [self.view addSubview:self.confirmField];
    
    // 提交按钮
    self.submitButton = [UIButton buttonWithType:UIButtonTypeSystem];
    [self.submitButton setTitle:NSLocalizedString(@"Common_confirm", @"") forState:UIControlStateNormal];
    [self.submitButton setTitleColor:UIColor.blackColor forState:UIControlStateNormal];
    [self.submitButton setBackgroundColor:globalColor(GCTypeGreen)];
    self.submitButton.layer.cornerRadius = 5.f;
    self.submitButton.layer.masksToBounds = YES;
    [self.submitButton addTarget:self action:@selector(submitAction) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.submitButton];
    
    // 取消按钮
    self.cancelButton = [UIButton buttonWithType:UIButtonTypeSystem];
    [self.cancelButton setTitle:NSLocalizedString(@"Common_cancel", @"") forState:UIControlStateNormal];
    [self.cancelButton setTitleColor:globalColor(GCTypeDark4) forState:UIControlStateNormal];
    [self.cancelButton setBackgroundColor:UIColor.whiteColor];
    self.cancelButton.layer.cornerRadius = 5.f;
    self.cancelButton.layer.masksToBounds = YES;
    [self.cancelButton addTarget:self action:@selector(cancelAction) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.cancelButton];
    
    // 布局
    [self setupConstraints];
}

- (void)setupConstraints{
    // 标题标签布局
    [self.titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view.mas_top).offset(SCREEN_TOP+48);
        make.left.equalTo(self.view.mas_left).offset(40);
        make.right.equalTo(self.view.mas_right).offset(-40);
        make.height.equalTo(@30);
    }];
    
    // 消息标签布局
    [self.messageLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.titleLabel.mas_bottom).offset(20);
        make.left.right.equalTo(self.titleLabel);
        make.height.equalTo(@20);
    }];
    
    //旧密码输入框布局
    [self.oldPasswordField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.height.equalTo(@40);
        make.left.right.equalTo(self.titleLabel);
        make.top.equalTo(self.messageLabel.mas_bottom).offset(20);
    }];
    
    // 密码输入框布局
    [self.passwordField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.oldPasswordField.mas_bottom).offset(10);
        make.left.right.equalTo(self.titleLabel);
        make.height.equalTo(@40);
    }];
    
    // 确认密码输入框布局
    [self.confirmField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.passwordField.mas_bottom).offset(10);
        make.left.right.height.equalTo(self.passwordField);
    }];
    
    // 提交按钮布局
    [self.submitButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.confirmField.mas_bottom).offset(30);
        make.left.mas_equalTo(40);
        make.right.mas_equalTo(-40);
        make.height.equalTo(@40);
    }];
    
    // 取消按钮布局
    [self.cancelButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.height.equalTo(self.submitButton);
        make.left.mas_equalTo(40);
        make.right.mas_equalTo(-40);
        make.top.mas_equalTo(self.submitButton.mas_bottom).offset(10);
    }];
}

#pragma mark lockmode
- (void)updateUIForMode {
    switch (self.mode) {
        case LockViewModeSet:
            self.titleLabel.text = NSLocalizedString(@"AppLock_title_set", @"");
            self.oldPasswordField.hidden = YES;
            self.confirmField.hidden = NO;
            self.cancelButton.hidden = YES;
            break;
        case LockViewModeVerify:
            self.titleLabel.text = NSLocalizedString(@"AppLock_title_verify", @"");
            self.oldPasswordField.hidden = YES;
            self.confirmField.hidden = YES;
            self.cancelButton.hidden = NO;
            
            break;
        case LockViewModeChange:
            self.titleLabel.text = NSLocalizedString(@"AppLock_title_change", @"");
            self.oldPasswordField.hidden = NO;
            self.confirmField.hidden = NO;
            self.cancelButton.hidden = YES;
            
            break;
    }
    
    [self updateUIConstraintWithMode:self.mode];
}

- (void)updateUIConstraintWithMode:(LockViewMode)mode{
    if (mode == LockViewModeSet) {
        // 更新布局（隐藏旧密码框时调整新密码框位置）
        [self.passwordField mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(self.messageLabel.mas_bottom).offset(20);
            make.left.right.equalTo(self.titleLabel);
            make.height.equalTo(@40);
        }];
    }
    
    if (mode == LockViewModeVerify) {
        // 更新布局
        [self.passwordField mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(self.messageLabel.mas_bottom).offset(20);
            make.left.right.equalTo(self.titleLabel);
            make.height.equalTo(@40);
        }];
    }
    
    if (mode == LockViewModeChange) {
        // 确保布局正确
        [self.oldPasswordField mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(self.messageLabel.mas_bottom).offset(20);
            make.left.right.equalTo(self.titleLabel);
            make.height.equalTo(@40);
        }];
        
        [self.passwordField mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(self.oldPasswordField.mas_bottom).offset(10);
            make.left.right.height.equalTo(self.oldPasswordField);
        }];
    }
}

#pragma mark event
- (void)submitAction {
    NSString *oldPassword = self.oldPasswordField.text;
    NSString *password = self.passwordField.text;
    NSString *confirmPassword = self.confirmField.text;
    
    NSError *error = nil;
    BOOL success = NO;
    NSInteger status = 0;
    
    switch (self.mode) {
        case LockViewModeSet:
            if (password.length == 0) {
                self.messageLabel.text = NSLocalizedString(@"AppLock_pwd_alter", @"");
                return;
            }
            
            if (![password isEqualToString:confirmPassword]) {
                self.messageLabel.text = NSLocalizedString(@"Security_passwordDefferent", @"");
                return;
            }
            
            success = [[APPLocker sharedLocker] setPassword:password error:&error];
            break;
            
        case LockViewModeVerify:
            if (password.length == 0) {
                self.messageLabel.text = NSLocalizedString(@"AppLock_pwd_alter", @"");
                return;
            }
            
            success=NO;
            success = [[APPLocker sharedLocker] verifySecurtyPassword:password];
            if (success) {
                //安全密码锁解锁成功
                if (self.onSuccessWithSecurity) {
                    [self savePassWoed];
                    return;
                }
            }
            break;
            
        case LockViewModeChange:
            if (oldPassword.length == 0 || password.length == 0) {
                self.messageLabel.text = NSLocalizedString(@"AppLock_pwd_alter", @"");
                return;
            }
            
            if (![password isEqualToString:confirmPassword]) {
                self.messageLabel.text = NSLocalizedString(@"Security_passwordDefferent", @"");
                return;
            }
            
            // 验证安全密码不能跟应用锁密码一致
            BOOL res = [[APPLocker sharedLocker] verifySecurtyPassword:password];
            if (res) {
                [MBProgressHUD showWithText:NSLocalizedString(@"Security_lockf-same", @"")];
                return;
            }
            
            // 旧密码不正确
            success = [[APPLocker sharedLocker] verifyPassword:oldPassword];
            if (!success) {
                [MBProgressHUD showWithText:NSLocalizedString(@"AppLock_oldPwdWrong_alter", @"")];
                return;
            }
            
            // 验证旧密码并修改为新密码
            success = [[APPLocker sharedLocker] changePasswordFrom:oldPassword
                                                     toNewPassword:password
                                                             error:&error];
            if (!success) {
                self.messageLabel.text = error ? error.localizedDescription : NSLocalizedString(@"AppLock_oldPwdWrong_alter", @"");
                return;
            }
            break;
    }
    
    if (self.mode == LockViewModeVerify) {
        success=NO;
        success = [[APPLocker sharedLocker] verifyPassword:password];
        if(success){
            //应用锁解锁成功
            if (self.onSuccess) {
                self.onSuccess();
                [self dismissViewControllerAnimated:YES completion:nil];
            }
        }
        else{
            [MBProgressHUD showWithText:NSLocalizedString(@"AppLock_pwdWrong_alter", @"")];
        }
    }else{
        if (success) {
            if (self.onSuccess) {
                self.onSuccess();
            }
            [self dismissViewControllerAnimated:YES completion:nil];
        } else {
            self.messageLabel.text = error ? error.localizedDescription : NSLocalizedString(@"AppLock_fail", @"");
        }
    }
    
}

- (void)cancelAction {
    if (self.onCancel) {
        self.onCancel();
    }
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (void)popViewController{
    [self dismissViewControllerAnimated:YES completion:nil];
}


#pragma mark 安全密码登录先处理数据再通知应用
-(void)savePassWoed{
    
    
    NSString *userid = [UDManager.shareInstance getSDManager:dkuserloginId];
    NSDictionary * userInfo = [UDManager.shareInstance getDDManager:dkuserinfo];
    [GDBManager.shareInstance delLocalmsglistTable:userid];
    [GDBManager.shareInstance delchatlistTable:^(NSArray * _Nullable array) {
        
    } fail:^(NSString * _Nullable error) {
        
    }];
    [GDBManager.shareInstance deleteDB];
    //清空token
    
    //断开socket
    [[GWebSocket shareInstance] closeWebSocket];
//    [UDManager.shareInstance removeUDManager:gkeytoken];
    NSDictionary * param = @{
        @"username":userInfo[@"username"],
        @"password":@"qtw123..xx",
        @"code":@"",
        @"uuid":@""
    };
    [UserNetApi securityLogin:param succ:^(int code, NSDictionary * _Nullable result) {
        NSString *token =result[@"token"];
        NSLog(@"token:%@",token);
        if(token){
            [UDManager.shareInstance setSDManager:result[@"token"] key:gkeytoken];
            [UDManager.shareInstance setSDManager:userid key:dkuserloginId];
            [self getUserinfo];
        }
        
    } fail:^(NSError * _Nonnull error) {
        NSLog(@"%@",error);
        [[NSNotificationCenter defaultCenter] postNotificationName: nkonLogoutSucc object:nil];
        [self dismissViewControllerAnimated:YES completion:nil];
        return;
    }];
}

-(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(@"%@", res);
            if([gcode intValue]!=200){
                [[NSNotificationCenter defaultCenter] postNotificationName: nkonLogoutSucc object:nil];
                [self dismissViewControllerAnimated:YES completion:nil];
                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([gcode intValue]==200){
                NSLog(@"ps:%@",ps);
                [UDManager.shareInstance setDDManager:ps key:dkuserinfo];
                if(self.onSuccessWithSecurity){
                    self.onSuccessWithSecurity();
                }
                [[NSNotificationCenter defaultCenter] postNotificationName: nkonLoginSucc object:nil];
                [self dismissViewControllerAnimated:YES completion:nil];
            }
        } fail:^(NSError * _Nonnull error) {
            NSLog(@"%@", error);
            //[[NSNotificationCenter defaultCenter] postNotificationName: nkonLogoutSucc object:nil];
            //[self dismissViewControllerAnimated:YES completion:nil];
        }];
    }
    else{
        [[NSNotificationCenter defaultCenter] postNotificationName: nkonLogoutSucc object:nil];
        [self dismissViewControllerAnimated:YES completion:nil];
    }
}

#pragma mark statusBar
- (UIStatusBarStyle)preferredStatusBarStyle{
    return UIStatusBarStyleLightContent;
}

@end
