//
//  DeleteAccountController.m
//  AIIM
//
//  Created by qitewei on 2025/5/11.
//

#import "DeleteAccountController.h"

#import "UDManager.h"
#import "UserNetApi.h"
#import "UserNetApi.h"


@interface DeleteAccountController ()
@property (nonatomic, strong) UIStackView * titleStackView;
@property (nonatomic, strong) UILabel * passwordTitle;
@property (nonatomic, strong) UILabel * codeTitle;
@property (nonatomic, strong) UITextField * passwordTextfield;
@property (nonatomic, strong) UITextField * codeTextfield;
@property (nonatomic, strong) UIButton * getCodeBtn;
@property (nonatomic, strong) UIButton * deleteBtn;

@property (nonatomic, strong) NSMutableDictionary * userInfo;
@property (nonatomic, strong) NSTimer *timer;
@property (nonatomic, assign) NSInteger remainingSeconds;
@end

@implementation DeleteAccountController

- (void)viewDidLoad {
    [super viewDidLoad];
    // 创建一个点击手势
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(dismissKeyboard)];
    // 将手势添加到主视图上
    [self.view addGestureRecognizer:tap];
    [self configUI];
}
-(void)dismissKeyboard{
    NSLog(@"dismissKeyboard");
    [self.view endEditing:YES];
}
- (void)configUI{
    [self setNavigationTitle:NSLocalizedString(@"userCenter-zhuxiaozh", @"")];
    // 设置导航栏背景色
    [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.view addSubview:self.titleStackView];
    [self.titleStackView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.height.mas_equalTo(128);
        make.left.mas_equalTo(20);
        make.top.mas_equalTo(SCREEN_TOP+48);
    }];
    
    [self.view addSubview:self.passwordTextfield];
    [self.passwordTextfield mas_makeConstraints:^(MASConstraintMaker *make) {
        make.height.mas_equalTo(50);
        make.left.mas_equalTo(104);
        make.right.mas_equalTo(-30);
        make.centerY.mas_equalTo(self.passwordTitle.mas_centerY);
    }];
    
    [self.view addSubview:self.codeTextfield];
    [self.codeTextfield mas_makeConstraints:^(MASConstraintMaker *make) {
        make.height.mas_equalTo(50);
        make.left.mas_equalTo(104);
        make.right.mas_equalTo(-30);
        make.centerY.mas_equalTo(self.codeTitle.mas_centerY);
    }];
    
    [self.view addSubview:self.getCodeBtn];
    [self.getCodeBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.size.mas_equalTo(CGSizeMake(125, 46));
        make.right.mas_equalTo(-20);
        make.top.mas_equalTo(self.codeTextfield.mas_bottom).offset(30);
    }];
    
    [self.view addSubview:self.deleteBtn];
    [self.deleteBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.height.mas_equalTo(46);
        make.left.mas_equalTo(20);
        make.right.mas_equalTo(-20);
        make.top.mas_equalTo(self.getCodeBtn.mas_bottom).offset(30);
    }];
}

#pragma mark event
- (void)getCodeButtonClicked{
    //发送验证码
    [UserNetApi getEmailcodereset:self.userInfo[@"username"] succ:^(int code, NSDictionary * _Nullable res) {
        NSLog(@"result:%@",res);
        if ([res jk_hasKey:@"code"] && [res[@"code"]  isEqual: @200]) {
            // 开始倒计时
            self.remainingSeconds = 60;
            [self startTimer];
            
            // 禁用按钮并改变样式
            self.getCodeBtn.enabled = NO;
            [self.getCodeBtn setTitleColor:[UIColor grayColor] forState:UIControlStateDisabled];
            [self.getCodeBtn setTitle:[NSString stringWithFormat:@"%@(%ld)",NSLocalizedString(@"Sign-wangjimm", @"验证码"), (long)self.remainingSeconds] forState:UIControlStateDisabled];
            
//            [AlertHelper showAlertWithTitle:@"" message:NSLocalizedString(@"Sign-yanzhengmts", @"") cancelButtonTitle:NSLocalizedString(@"Common_getIt", @"") confirmButtonTitle:nil completion:^(NSInteger buttonIndex) {
//                
//            }];
        }else{
            [MBProgressHUD showWithText:res[@"msg"]];
        }
    } fail:^(NSError * _Nonnull error) {
        NSLog(@"error:%@",error);
        [MBProgressHUD showWithText:NSLocalizedString(@"Login_network_alter", @"")];
    }];
}

- (void)deleteAccountButtonClicked{
    if (self.passwordTextfield.text.length == 0) {
        [MBProgressHUD showWithText:NSLocalizedString(@"Sign-passw-note", @"")];
        return;
    }
    
    if (self.codeTextfield.text.length == 0) {
        [MBProgressHUD showWithText:NSLocalizedString(@"Sign-qingsryzm", @"")];
        return;
    }
    
//    [AlertHelper showAlertWithTitle:NSLocalizedString(@"Common_tips", @"") message:NSLocalizedString(@"Security_deleteAccount_alter", @"") cancelButtonTitle:NSLocalizedString(@"Common_cancel", @"") confirmButtonTitle:NSLocalizedString(@"Common_deleteAccount", @"") completion:^(NSInteger buttonIndex) {
//        
//        if (buttonIndex == 0) {
//            [self deleteAccount];
//        }
//    }];
}

#pragma mark api
- (void)deleteAccount{
    NSDictionary * param = @{
        @"username":self.userInfo[@"username"],
        @"password":self.passwordTextfield.text,
        @"code":self.codeTextfield.text,
        @"uuid":@""
    };
    
    [UserNetApi zhuxiaozhanghao:param succ:^(int code, NSDictionary * _Nullable res) {
        if ([res jk_hasKey:@"msg"]) {
            [MBProgressHUD showWithText:res[@"msg"]];
        }
        
        if ([res jk_hasKey:@"code"] && [res[@"code"] isEqual:@200]) {
//            [UDManager.shareInstance removeUDManager:gkeytoken];
//            [UDManager.shareInstance removeUDManager:dkuserloginId];
//            [UDManager.shareInstance removeUDManager:dkuserinfo];
////            [[NSNotificationCenter defaultCenter] postNotificationName: nkonLogoutSucc object:nil];
//            [[LoginStateManager sharedManager] clearLoginStatus];
        }
    } fail:^(NSError * _Nonnull error) {
        NSLog(@"error%@",error);
    }];
}

#pragma mark timer
- (void)startTimer {
    if (!self.timer) {
        self.timer = [NSTimer scheduledTimerWithTimeInterval:1.0
                                                       target:self
                                                     selector:@selector(updateTimer:)
                                                     userInfo:nil
                                                      repeats:YES];
        [[NSRunLoop mainRunLoop] addTimer:self.timer forMode:NSRunLoopCommonModes];
    }
}

- (void)updateTimer:(NSTimer *)timer {
    self.remainingSeconds--;
    
    if (self.remainingSeconds <= 0) {
        [self stopTimer];
        
        // 恢复按钮状态
        self.getCodeBtn.enabled = YES;
        [self.getCodeBtn setTitle:NSLocalizedString(@"Sign-huoquyzm", @"") forState:UIControlStateNormal];
    } else {
        [self.getCodeBtn setTitle:[NSString stringWithFormat:@"%@(%ld)",NSLocalizedString(@"Sign-wangjimm", @"验证码"), (long)self.remainingSeconds] forState:UIControlStateDisabled];
    }
}

- (void)stopTimer {
    if (self.timer) {
        [self.timer invalidate];
        self.timer = nil;
    }
}

- (void)dealloc {
    [self stopTimer];
}

#pragma mark lazy
- (UIStackView *)titleStackView{
    if (!_titleStackView) {
        _titleStackView = [[UIStackView alloc] initWithArrangedSubviews:@[self.passwordTitle,self.codeTitle]];
        _titleStackView.axis = UILayoutConstraintAxisVertical;
        _titleStackView.alignment = UIStackViewAlignmentFill;
        _titleStackView.distribution = UIStackViewDistributionEqualSpacing;
        _titleStackView.spacing = 64;
    }
    return _titleStackView;
}

- (UILabel *)passwordTitle{
    if (!_passwordTitle) {
        _passwordTitle = [[UILabel alloc] init];
        _passwordTitle.text = NSLocalizedString(@"Common_password", @"");
        _passwordTitle.textColor = UIColor.whiteColor;
        _passwordTitle.font = SYSFONT(16);
    }
    return _passwordTitle;
}

- (UILabel *)codeTitle{
    if (!_codeTitle) {
        _codeTitle = [[UILabel alloc] init];
        _codeTitle.text = NSLocalizedString(@"Sign-wangjimm", @"");
        _codeTitle.textColor = UIColor.whiteColor;
        _codeTitle.font = SYSFONT(16);
    }
    return _codeTitle;
}

- (UITextField *)passwordTextfield{
    if (!_passwordTextfield) {
        _passwordTextfield = [[UITextField alloc] init];
        _passwordTextfield.textColor = UIColor.whiteColor;
        _passwordTextfield.borderStyle = UITextBorderStyleNone;
        _passwordTextfield.layer.borderWidth = 1.f;
        _passwordTextfield.layer.borderColor = globalColor(GCTypeDark2).CGColor;
        _passwordTextfield.layer.cornerRadius = 5.f;
        _passwordTextfield.secureTextEntry = YES;
        _passwordTextfield.leftViewMode = UITextFieldViewModeAlways;
        UIView * leftView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 15, 50)];
        _passwordTextfield.leftView = leftView;
    }
    return _passwordTextfield;
}

- (UITextField *)codeTextfield{
    if (!_codeTextfield) {
        _codeTextfield = [[UITextField alloc] init];
        _codeTextfield.textColor = UIColor.whiteColor;
        _codeTextfield.borderStyle = UITextBorderStyleNone;
        _codeTextfield.layer.borderWidth = 1.f;
        _codeTextfield.layer.borderColor = globalColor(GCTypeDark2).CGColor;
        _codeTextfield.layer.cornerRadius = 5.f;
        _codeTextfield.leftViewMode = UITextFieldViewModeAlways;
        UIView * leftView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 15, 50)];
        _codeTextfield.leftView = leftView;
    }
    return _codeTextfield;
}

- (UIButton *)getCodeBtn{
    if (!_getCodeBtn) {
        _getCodeBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [_getCodeBtn setBackgroundColor:globalColor(GCTypeGreen)];
        [_getCodeBtn setTitle:NSLocalizedString(@"Sign-huoquyzm", @"") forState:UIControlStateNormal];
        [_getCodeBtn setTitleColor:UIColor.blackColor forState:UIControlStateNormal];
        _getCodeBtn.titleLabel.font = SYSMFONT(14);
        _getCodeBtn.layer.cornerRadius = 5.f;
        _getCodeBtn.layer.masksToBounds = YES;
        [_getCodeBtn addTarget:nil action:@selector(getCodeButtonClicked) forControlEvents:UIControlEventTouchUpInside];
    }
    return _getCodeBtn;
}

- (UIButton *)deleteBtn{
    if (!_deleteBtn) {
        _deleteBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [_deleteBtn setBackgroundColor:globalColor(GCTypeGreen)];
        [_deleteBtn setTitle:NSLocalizedString(@"userCenter-zhuxiaozh", @"") forState:UIControlStateNormal];
        [_deleteBtn setTitleColor:UIColor.blackColor forState:UIControlStateNormal];
        _deleteBtn.titleLabel.font = SYSMFONT(16);
        _deleteBtn.layer.cornerRadius = 5.f;
        _deleteBtn.layer.masksToBounds = YES;
        [_deleteBtn addTarget:nil action:@selector(deleteAccountButtonClicked) forControlEvents:UIControlEventTouchUpInside];
        
    }
    return _deleteBtn;
}

- (NSMutableDictionary *)userInfo{
    if (!_userInfo) {
        _userInfo = [NSMutableDictionary dictionaryWithDictionary:[UDManager.shareInstance getDDManager:dkuserinfo]];
    }
    return _userInfo;
}

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

@end
