//
//  GCoverController.m
//  aiim
//
//  Created by gan on 2025/2/28.
//

#import "GCoverController.h"

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


@interface GCoverController ()
@property (nonatomic, strong) UILabel * titleLbl;
@property (nonatomic, strong) UIButton * leftBtn;
@property (nonatomic, strong) UIStackView * titleStackView;
@property (nonatomic, strong) UILabel * nameTitleLbl;
@property (nonatomic, strong) UILabel * resePwdTitleLbl;
@property (nonatomic, strong) UILabel * confirmPwdTitleLbl;
@property (nonatomic, strong) UILabel * codeTitleLbl;
@property (nonatomic, strong) UITextField * nameTextfield;
@property (nonatomic, strong) UITextField * resetPwdTextfield;
@property (nonatomic, strong) UITextField * confirmPwdTextfield;
@property (nonatomic, strong) UITextField * codeTextfield;
@property (nonatomic, strong) UIButton * getCodeBtn;
@property (nonatomic, strong) UIButton * saveBtn;

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

@implementation GCoverController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    NSLog(@"GCoverController viewDidLoad");
    [self configUI];
}

#pragma mark UI
- (void)configUI{
//    self.view.backgroundColor = UIColor.blackColor;
    
    UIImageView * bgImageView = [[UIImageView alloc] initWithImage:kImageMake(@"loginBG")];
    [self.view addSubview:bgImageView];
    [bgImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.top.bottom.mas_equalTo(0);
    }];
    
    if (self.isLogin) {
        [self.titles addObjectsFromArray:@[self.resePwdTitleLbl,self.confirmPwdTitleLbl,self.codeTitleLbl]];
    }else{
        [self.titles addObjectsFromArray:@[self.nameTitleLbl,self.resePwdTitleLbl,self.confirmPwdTitleLbl,self.codeTitleLbl]];
    }
    
    [self.view addSubview:self.titleLbl];
    [self.titleLbl mas_makeConstraints:^(MASConstraintMaker *make) {
        make.height.mas_equalTo(16);
        make.centerX.mas_equalTo(self.view.mas_centerX);
        make.top.mas_equalTo(STATUS_Height+16);
    }];
    
    [self.view addSubview:self.leftBtn];
    [self.leftBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.size.mas_equalTo(CGSizeMake(20, 20));
        make.left.mas_equalTo(20);
        make.centerY.mas_equalTo(self.titleLbl.mas_centerY);
    }];
    
    [self.view addSubview:self.titleStackView];
    [self.titleStackView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.height.mas_equalTo(16*self.titles.count + 64*(self.titles.count-1) + 32);
        make.left.mas_equalTo(20);
        make.top.mas_equalTo(self.titleLbl.mas_bottom).offset(32);
    }];
    
    if (!self.isLogin) {
        [self.view addSubview:self.nameTextfield];
        [self.nameTextfield mas_makeConstraints:^(MASConstraintMaker *make) {
            make.height.mas_equalTo(50);
            make.left.mas_equalTo(104);
            make.right.mas_equalTo(-20);
            make.centerY.mas_equalTo(self.nameTitleLbl.mas_centerY);
        }];
    }
    
    [self.view addSubview:self.resetPwdTextfield];
    [self.resetPwdTextfield mas_makeConstraints:^(MASConstraintMaker *make) {
        make.height.mas_equalTo(50);
        make.left.mas_equalTo(104);
        make.right.mas_equalTo(-20);
        make.centerY.mas_equalTo(self.resePwdTitleLbl.mas_centerY);
    }];
    
    [self.view addSubview:self.confirmPwdTextfield];
    [self.confirmPwdTextfield mas_makeConstraints:^(MASConstraintMaker *make) {
        make.height.mas_equalTo(50);
        make.left.mas_equalTo(104);
        make.right.mas_equalTo(-20);
        make.centerY.mas_equalTo(self.confirmPwdTitleLbl.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(-20);
        make.centerY.mas_equalTo(self.codeTitleLbl.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.saveBtn];
    [self.saveBtn 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)leftButtonClicked{
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (void)getCodeButtonClicked{
    
    if (self.nameTextfield.text.length == 0 && !self.isLogin) {
        [MBProgressHUD showWithText:NSLocalizedString(@"Sign-usernme-note", @"")];
        return;
    }
    //发送验证码
    [UserNetApi getEmailcodereset:self.isLogin ? self.userInfo[@"username"] : self.nameTextfield.text 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) {
//                [self.codeTextfield becomeFirstResponder];
//            }];
        }else{
            [MBProgressHUD showWithText:res[@"msg"]];
        }
    } fail:^(NSError * _Nonnull error) {
        NSLog(@"error:%@",error);
        [MBProgressHUD showWithText:NSLocalizedString(@"Login_network_alter", @"")];
    }];
}

- (void)saveButtonClicked{
    if (self.nameTextfield.text.length == 0 && !self.isLogin) {
        [MBProgressHUD showWithText:NSLocalizedString(@"login-usernme-note", @"")];
        return;
    }
    
    if (self.resetPwdTextfield.text.length == 0) {
        [MBProgressHUD showWithText:NSLocalizedString(@"Security_newPassword_alter", @"")];
        return;
    }
    
    if (![self.confirmPwdTextfield.text isEqualToString:self.resetPwdTextfield.text]) {
        [MBProgressHUD showWithText:NSLocalizedString(@"PwdChange_passwordsDifferent_alter", @"")];
        return;
    }
    
    if (self.codeTextfield.text.length == 0) {
        [MBProgressHUD showWithText:NSLocalizedString(@"Sign-qingsryzm", @"")];
        return;
    }
    
    NSDictionary * param = @{
        @"username": self.isLogin ? self.userInfo[@"username"] : self.nameTextfield.text, //用户名
        @"password": self.resetPwdTextfield.text, //用户密码
        @"code": self.codeTextfield.text, //验证码
        @"uuid": @"" //唯一标识
    };
    
    [UserNetApi resetPassword:param succ:^(int code, NSDictionary * _Nullable res) {
        NSLog(@"result:%@",res);
        if ([res jk_hasKey:@"msg"]) {
            [MBProgressHUD showWithText:res[@"msg"]];
        }
        
        if ([res jk_hasKey:@"code"] && [res[@"code"] integerValue] == 200 && self.isLogin) {
            //退出登录
            //[[LoginStateManager sharedManager] logout];
        }
        
    } 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
- (UILabel *)titleLbl{
    if (!_titleLbl) {
        _titleLbl = [[UILabel alloc] init];
        _titleLbl.text = NSLocalizedString(@"userCenter-chongzhimm", @"");
        _titleLbl.textColor = UIColor.whiteColor;
        _titleLbl.font = SYSMFONT(16);
        _titleLbl.textAlignment = NSTextAlignmentCenter;
    }
    return _titleLbl;
}

- (UIButton *)leftBtn{
    if (!_leftBtn) {
        _leftBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [_leftBtn setImage:kImageMake(@"fanhui") forState:UIControlStateNormal];
        [_leftBtn addTarget:nil action:@selector(leftButtonClicked) forControlEvents:UIControlEventTouchUpInside];
//        [_leftBtn jk_addActionHandler:^(NSInteger tag) {
//            [self leftButtonClicked];
//        }];
    }
    return _leftBtn;
}

- (UIStackView *)titleStackView{
    if (!_titleStackView) {
        _titleStackView = [[UIStackView alloc] initWithArrangedSubviews:self.titles];
        _titleStackView.axis = UILayoutConstraintAxisVertical;
        _titleStackView.alignment = UIStackViewAlignmentFill;
        _titleStackView.distribution = UIStackViewDistributionEqualSpacing;
        _titleStackView.spacing = 64;
    }
    return _titleStackView;
}

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

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

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

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

- (NSMutableArray *)titles{
    if (!_titles) {
        _titles = [NSMutableArray array];
    }
    return _titles;
}

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

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

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

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

- (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;
        _codeTextfield.keyboardType = UIKeyboardTypeNumberPad;
    }
    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];
//        [_getCodeBtn jk_addActionHandler:^(NSInteger tag) {
//            [self getCodeButtonClicked];
//        }];
    }
    return _getCodeBtn;
}

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

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

@end
