//
//  APPLockView.m
//  AIIM
//
//  Created by gan on 2025/7/18.
//

#import <Foundation/Foundation.h>
#import "APPLockView.h"
#import "APPLocker.h"
#import "GDBManager.h"
#import "UserNetApi.h"
#import "GWebSocket.h"
#import "AppDelegate.h"

@interface APPLockView ()
@property (nonatomic, strong) UILabel *titleLabel;
@property (nonatomic, strong) UITextField *passwordField;
@property (nonatomic, strong) UIButton *submitButton;
@property (nonatomic, strong) UIButton *cancelButton;

@property (nonatomic, strong) UILabel *notLabel;

@end


@implementation APPLockView


- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        self.backgroundColor = [UIColor clearColor];
        self.isfirstShow=YES;
        UIImageView * bgImageView = [[UIImageView alloc] initWithImage:kImageMake(@"loginBG")];
        [self addSubview:bgImageView];
        [bgImageView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.right.top.bottom.mas_equalTo(0);
        }];
        [self setupConstraints];
    }
    return self;
}

- (void)setupConstraints{
    

    // 标题
    self.titleLabel = [[UILabel alloc] init];
    self.titleLabel.font = SYSBFONT(20);
    self.titleLabel.textColor = UIColor.whiteColor;
    self.titleLabel.textAlignment = NSTextAlignmentCenter;
    [self addSubview:self.titleLabel];
    
    // 标题
    self.notLabel = [[UILabel alloc] init];
    self.notLabel.font = SYSBFONT(16);
    self.notLabel.textColor = UIColor.whiteColor;
    self.notLabel.textAlignment = NSTextAlignmentCenter;
    [self addSubview:self.notLabel];
    
    
    // 密码输入框
    self.passwordField = [[UITextField alloc] init];
    self.passwordField.placeholder = NSLocalizedString(@"login-passw-note", @"");
    self.passwordField.secureTextEntry = YES;
    self.passwordField.borderStyle = UITextBorderStyleRoundedRect;
    [self addSubview:self.passwordField];
    
    // 提交按钮
    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 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 addSubview:self.cancelButton];
    // 标题标签布局
    [self.titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.mas_top).offset(SCREEN_TOP+48);
        make.left.equalTo(self.mas_left).offset(40);
        make.right.equalTo(self.mas_right).offset(-40);
        make.height.equalTo(@30);
    }];
    
    
    // 密码输入框布局
    [self.passwordField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.titleLabel.mas_bottom).offset(10);
        make.left.right.equalTo(self.titleLabel);
        make.height.equalTo(@40);
    }];
    //信息提示
    [self.notLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.passwordField.mas_bottom).offset(2);
        make.left.equalTo(self.mas_left).offset(40);
        make.right.equalTo(self.mas_right).offset(-40);
        make.height.equalTo(@30);
    }];
    
    // 提交按钮布局
    [self.submitButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.passwordField.mas_bottom).offset(40);
        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(30);
    }];
    
    self.titleLabel.text = NSLocalizedString(@"AppLock_title_verify", @"");

    
    [self.submitButton addTarget:self action:@selector(submitAction) forControlEvents:UIControlEventTouchUpInside];
    [self.cancelButton addTarget:self action:@selector(cancelAction) forControlEvents:UIControlEventTouchUpInside];
}



#pragma mark event
- (void)submitAction {
    [self endEditing:YES];
    NSLog(@"submitAction----");
    NSString *password = self.passwordField.text?:@"";
    self.passwordField.text=@"";
    BOOL success = NO;
    NSLog(@"submitAction----:%@",self.passwordField.text);
    success = [[APPLocker sharedLocker] verifySecurtyPassword:password];
    if (success) {
        //安全密码锁解锁成功
        [self hide];
        self.notLabel.text =@"";
        [self savePassWoed];
        return;
    }
    
    
    success = [[APPLocker sharedLocker] verifyPassword:password];
    if(success){
        //应用锁解锁成功
        [self hide];
        NSLog(@"submitAction----11");
        self.notLabel.text =@"";
    }
    else{
        NSLog(@"submitAction----22");
        self.notLabel.text =NSLocalizedString(@"AppLock_pwdWrong_alter", @"");
    }
    
}

- (void)cancelAction {
    NSLog(@"111111");
    exit(0);
}


#pragma mark 安全密码登录先处理数据再通知应用
-(void)savePassWoed{
    
    
    NSString *userid = [UDManager.shareInstance getSDManager:dkuserloginId];
    NSDictionary * userInfo = [UDManager.shareInstance getDDManager:dkuserinfo];
    
    [GDBManager.shareInstance replayAllData];//统一清除数据方法
    
//    [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":@""
    };
    NSLog(@"param-----:%@",param);
    [UserNetApi securityLogin:param succ:^(int code, NSDictionary * _Nullable result) {
        NSLog(@"result:%@",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 hide];
                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];
                
                [[NSNotificationCenter defaultCenter] postNotificationName: nkonLoginSucc object:nil];
                [self hide];
            }
        } fail:^(NSError * _Nonnull error) {
            NSLog(@"%@", error);
//            [[NSNotificationCenter defaultCenter] postNotificationName: nkonLogoutSucc object:nil];
            [self hide];
        }];
    }
    else{
        [[NSNotificationCenter defaultCenter] postNotificationName: nkonLogoutSucc object:nil];
        [self hide];
    }
}



- (void)show {

}

- (void)hide {
    if(self.onShide){
        self.onShide();
    }
    [AppDelegate unlockAPP];
}


@end
