//
//  PersonalInfoController.m
//  AIIM
//
//  Created by qitewei on 2025/4/29.
//

#import "PersonalInfoController.h"

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

@interface PersonalInfoController ()<UITextFieldDelegate,UINavigationControllerDelegate,UIImagePickerControllerDelegate>
@property (nonatomic, strong) UIImageView * avatarImageView;
@property (nonatomic, strong) UIButton * avaterEditBtn;
@property (nonatomic, strong) UIStackView * titleStackView;
@property (nonatomic, strong) UILabel * nameLbl;
@property (nonatomic, strong) UILabel * signLbl;
@property (nonatomic, strong) UILabel * emailLbl;
@property (nonatomic, strong) UILabel * mobileLbl;
@property (nonatomic, strong) UILabel * genderLbl;
@property (nonatomic, strong) UITextField * nameTextfield;//用户名
@property (nonatomic, strong) UITextField * signTextfield;//昵称
@property (nonatomic, strong) UITextField * emailTextfield;
@property (nonatomic, strong) UITextField * mobileTextfield;
@property (nonatomic, strong) UITextField * genderTextfield;
@property (nonatomic, strong) UIButton * saveBtn;

@property (nonatomic, strong) NSMutableDictionary * userInfo;
@end

@implementation PersonalInfoController

#pragma mark lifecircle
- (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];
}

#pragma mark UI
- (void)configUI{
    [self setNavigationBarHidden:NO animated:YES];
    [self setNavigationTitle:NSLocalizedString(@"userCenter-gerenxinx", @"")];
    // 设置导航栏背景色
    [self setNavigationBarTransparent:YES];
    [self setNavigationBarBackgroundColor:UIColor.clearColor];
    
    // 设置标题颜色和字体
    [self setNavigationTitleColor:[UIColor whiteColor] font:[UIFont boldSystemFontOfSize:16]];
    
    // 设置返回按钮
    [self setBackButtonTitle:@""];
    [self setBackButtonColor:[UIColor whiteColor]];
    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);
    }];
    
    [self.view addSubview:self.avatarImageView];
    [self.avatarImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.size.mas_equalTo(CGSizeMake(88, 88 ));
        make.top.mas_equalTo(120);
        make.centerX.mas_equalTo(self.view.mas_centerX);
    }];
    
    [self.view addSubview:self.avaterEditBtn];
    [self.avaterEditBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.size.mas_equalTo(CGSizeMake(28, 28));
        make.bottom.mas_equalTo(self.avatarImageView.mas_bottom);
        make.right.mas_equalTo(self.avatarImageView.mas_right);
    }];
    
    [self.view addSubview:self.titleStackView];
    [self.titleStackView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.height.mas_equalTo(310);
        make.left.mas_equalTo(20);
        make.top.mas_equalTo(self.avatarImageView.mas_bottom).offset(38);
        make.width.mas_equalTo(64);
    }];
    
    [self.view addSubview:self.nameTextfield];
    [self.nameTextfield mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(self.titleStackView.mas_right).offset(20);
        make.height.mas_equalTo(50);
        make.right.mas_equalTo(-20);
        make.centerY.mas_equalTo(self.nameLbl.mas_centerY);
    }];
    
    [self.view addSubview:self.signTextfield];
    [self.signTextfield mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(self.titleStackView.mas_right).offset(20);
        make.height.mas_equalTo(50);
        make.right.mas_equalTo(-20);
        make.centerY.mas_equalTo(self.signLbl.mas_centerY);
    }];
    
    [self.view addSubview:self.emailTextfield];
    [self.emailTextfield mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(self.titleStackView.mas_right).offset(20);
        make.height.mas_equalTo(50);
        make.right.mas_equalTo(-20);
        make.centerY.mas_equalTo(self.emailLbl.mas_centerY);
    }];
    
    [self.view addSubview:self.mobileTextfield];
    [self.mobileTextfield mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(self.titleStackView.mas_right).offset(20);
        make.height.mas_equalTo(50);
        make.right.mas_equalTo(-20);
        make.centerY.mas_equalTo(self.mobileLbl.mas_centerY);
    }];
    
    [self.view addSubview:self.genderTextfield];
    [self.genderTextfield mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(self.titleStackView.mas_right).offset(20);
        make.height.mas_equalTo(50);
        make.right.mas_equalTo(-20);
        make.centerY.mas_equalTo(self.genderLbl.mas_centerY);
    }];
    
    [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.genderTextfield.mas_bottom).offset(30);
    }];
    
    [self.avatarImageView sd_setImageWithURL:getURL(self.userInfo[@"avatar"]) placeholderImage:kImageMake(@"Avatar")];
    self.nameTextfield.text = self.userInfo[@"username"];
    self.signTextfield.text = self.userInfo[@"name"];
    self.emailTextfield.text = self.userInfo[@"email"];
    self.mobileTextfield.text = self.userInfo[@"mobile"];
    self.genderTextfield.text =  [self.userInfo[@"sex"] isEqualToString:@"0"] ? @"男": @"女";
    _genderLbl.alpha = 0;
    _genderTextfield.alpha = 0;
}


-(BOOL)isValidEmail:(NSString *)email {
    if(email.length==0){
        return true;
    }
    NSString *emailRegex = @"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,64}";
    NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex];
    
    return [emailTest evaluateWithObject:email];
}

#pragma mark event
- (void)saveButtonClicked{
    
    if (self.mobileTextfield.text.length<5&&self.mobileTextfield.text.length>0) {
        [MBProgressHUD showWithText:@"请输入有效的手机号"];
        return;
    }
    
    if (![self isValidEmail:self.emailTextfield.text]) {
        [MBProgressHUD showWithText:@"请输入有效的邮箱"];
        return;
    }
    
    
    
    NSDictionary * param = @{
        @"id":self.userInfo[@"id"],
        @"name":self.signTextfield.text.length == 0 ? @"" : self.signTextfield.text,
        @"email":self.emailTextfield.text,
        @"mobile":self.mobileTextfield.text.length == 0 ? @"" : self.mobileTextfield.text,
        @"sex":[self.genderTextfield.text isEqualToString:@"男"]?@"0" :@"1",
        @"avatar":self.userInfo[@"avatar"]
    };
    
    [UserNetApi changeUserInfo:param succ:^(int code, NSDictionary * _Nullable res) {
        if ([res jk_hasKey:@"msg"]) {
            [MBProgressHUD showWithText:[res objectForKey:@"msg"]];
        }
        
        if ([res jk_hasKey:@"code"]) {
            NSNumber * resCode = res[@"code"];
            if ([resCode integerValue] == 200) {
                NSDictionary *ps = @{@"avatar": self.userInfo[@"avatar"]?:@"",
                                     @"deptId": self.userInfo[@"deptId"]?:@"",
                                     @"email":self.emailTextfield.text?:@"",
                                     @"id":self.userInfo[@"id"]?:@"",
                                     @"mobile":self.mobileTextfield.text?:@"",
                                     @"name":self.signTextfield.text?:@"",
                                     @"sex":[self.genderTextfield.text isEqualToString:@"男"]?@"0":@"1",
                                     @"username":self.userInfo[@"username"]?:@"",
                                    };
                [UDManager.shareInstance setDDManager:ps key:dkuserinfo];
                !self->_infoRefreshBlock ?: self->_infoRefreshBlock();
            }
        }
    } fail:^(NSError * _Nonnull error) {
        [MBProgressHUD showWithText:@"修改失败"];
    }];

}

- (void)avatarEditButtonClicked{
    [self openImagePicker];
}

#pragma mark textfield delegate
- (void)textFieldDidEndEditing:(UITextField *)textField{
    textField.layer.borderColor = UIColor.lightGrayColor.CGColor;
}

- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField{
    textField.layer.borderColor = globalColor(GCTypeGreen).CGColor;
    textField.textColor = UIColor.whiteColor;
    if (textField == self.genderTextfield) {
        //性别弹窗
        [self showGenderSelectionAlert];
        return NO;
    }
    return YES;
}
 
- (void)showGenderSelectionAlert {
    // 创建 UIAlertController
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"选择性别" message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    
    // 添加男性选项
    UIAlertAction *maleAction = [UIAlertAction actionWithTitle:@"男" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        NSLog(@"选择了男");
        // 在这里处理选择男性的逻辑
    }];
    
    // 添加女性选项
    UIAlertAction *femaleAction = [UIAlertAction actionWithTitle:@"女" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        NSLog(@"选择了女");
        // 在这里处理选择女性的逻辑
    }];
    
    // 添加其他选项
    UIAlertAction *otherAction = [UIAlertAction actionWithTitle:@"其他" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        NSLog(@"选择了其他");
        // 在这里处理选择其他的逻辑
    }];
    
    // 添加取消选项
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        NSLog(@"取消了选择");
        // 在这里处理取消的逻辑，通常是可选的
    }];
    
    // 将操作添加到 UIAlertController 中
    [alertController addAction:maleAction];
    [alertController addAction:femaleAction];
    [alertController addAction:otherAction];
    [alertController addAction:cancelAction];
    
    // 显示 UIAlertController
    [self presentViewController:alertController animated:YES completion:nil];
}
 


#pragma mark imagePicker
- (void)openImagePicker {
    UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init];
    imagePicker.delegate = self;
    imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary; // 或者使用UIImagePickerControllerSourceTypeCamera
    [self presentViewController:imagePicker animated:YES completion:nil];
}


- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info {
    UIImage *chosenImage = info[UIImagePickerControllerEditedImage]; // 如果你设置了允许编辑，则使用这个键；否则使用UIImagePickerControllerOriginalImage
    if (!chosenImage) {
        chosenImage = info[UIImagePickerControllerOriginalImage];
    }
    // 裁剪图片，例如裁剪成一个圆形头像
    chosenImage = [self imageWithImage:chosenImage scaledToFillSize:CGSizeMake(100, 100)]; // 假设我们想要一个100x100的圆形头像
    [self dismissViewControllerAnimated:YES completion:nil];
    // 现在你可以调用上传图片的方法了
    [self uploadProfilePicture:chosenImage];
}
 
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
    [self dismissViewControllerAnimated:YES completion:nil];
}
- (UIImage *)imageWithImage:(UIImage *)image scaledToFillSize:(CGSize)size {
    UIGraphicsBeginImageContextWithOptions(size, NO, image.scale);
    UIBezierPath *path = [UIBezierPath bezierPathWithOvalInRect:CGRectMake(0, 0, size.width, size.height)];
    [path addClip];
    [image drawInRect:CGRectMake(0, 0, size.width, size.height)];
    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return newImage;
}

- (void)uploadProfilePicture:(UIImage *)image {
    NSDate *now = [NSDate date];
    NSTimeInterval trt = [now timeIntervalSince1970];
    NSInteger time = trt*1000;
    
    NSString *fileName = [NSString stringWithFormat:@"%ld.png",(long)time];
    NSData *imageData = UIImagePNGRepresentation(image);
    [GroupNetApi upLoaddataWToken:imageData fileName:fileName succ:^(int code, NSDictionary * res) {
        NSLog(@"res:%@",res);
        [self.avatarImageView sd_setImageWithURL:getURL(res[@"url"]) placeholderImage:kImageMake(@"Avatar")];
        [self.userInfo setObject:res[@"url"] forKey:@"avatar"];
    } fail:^(NSError * _Nonnull error) {
        ;
    }];
    
}

#pragma mark lazy
- (UIImageView *)avatarImageView{
    if (!_avatarImageView) {
        _avatarImageView = [[UIImageView alloc] init];
        _avatarImageView.contentMode = UIViewContentModeScaleAspectFit;
        _avatarImageView.layer.cornerRadius = 44.f;
        _avatarImageView.layer.borderColor = UIColor.whiteColor.CGColor;
        _avatarImageView.layer.borderWidth = 3.f;
        _avatarImageView.layer.masksToBounds = YES;
    }
    return _avatarImageView;
}

- (UIButton *)avaterEditBtn{
    if (!_avaterEditBtn) {
        _avaterEditBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [_avaterEditBtn setImage:[UIImage imageNamed:@"avatar_edit"] forState:UIControlStateNormal];
        [_avaterEditBtn setBackgroundColor:UIColor.whiteColor];
        _avaterEditBtn.layer.cornerRadius = 14.f;
        _avaterEditBtn.layer.masksToBounds = YES;
        [_avaterEditBtn addTarget:nil action:@selector(avatarEditButtonClicked) forControlEvents:UIControlEventTouchUpInside];
    }
    return _avaterEditBtn;
}

- (UILabel *)nameLbl{
    if (!_nameLbl) {
        _nameLbl = [[UILabel alloc] init];
        _nameLbl.text = NSLocalizedString(@"UserInfo_userName", @"");
        _nameLbl.textColor = UIColor.whiteColor;
        _nameLbl.font = [UIFont systemFontOfSize:16 weight:UIFontWeightRegular];
    }
    return _nameLbl;
}

- (UILabel *)signLbl{
    if (!_signLbl) {
        _signLbl = [[UILabel alloc] init];
        _signLbl.text = NSLocalizedString(@"UserInfo_nickName", @"");
        _signLbl.textColor = UIColor.whiteColor;
        _signLbl.font = [UIFont systemFontOfSize:16 weight:UIFontWeightRegular];
    }
    return _signLbl;
}

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

- (UILabel *)mobileLbl{
    if (!_mobileLbl) {
        _mobileLbl = [[UILabel alloc] init];
        _mobileLbl.text = NSLocalizedString(@"UserInfo_phoneNumber", @"");
        _mobileLbl.textColor = UIColor.whiteColor;
        _mobileLbl.font = [UIFont systemFontOfSize:16 weight:UIFontWeightRegular];
    }
    return _mobileLbl;
}

- (UILabel *)genderLbl{
    if (!_genderLbl) {
        _genderLbl = [[UILabel alloc] init];
        _genderLbl.text = NSLocalizedString(@"UserInfo_gender", @"");
        _genderLbl.textColor = UIColor.whiteColor;
        _genderLbl.font = [UIFont systemFontOfSize:16 weight:UIFontWeightRegular];
    }
    return _genderLbl;
}

- (UIStackView *)titleStackView{
    if (!_titleStackView) {
        _titleStackView = [[UIStackView alloc] initWithArrangedSubviews:@[self.nameLbl,self.signLbl,self.emailLbl,self.mobileLbl,self.genderLbl]];
        _titleStackView.axis = UILayoutConstraintAxisVertical;
        _titleStackView.alignment = UIStackViewAlignmentFill;
        _titleStackView.distribution = UIStackViewDistributionEqualSpacing;
        _titleStackView.spacing = 54.f;
    }
    return _titleStackView;
}

- (UITextField *)nameTextfield{
    if (!_nameTextfield) {
        _nameTextfield = [[UITextField alloc] init];
        _nameTextfield.textColor = UIColor.whiteColor;
        _nameTextfield.borderStyle = UITextBorderStyleNone;
        _nameTextfield.delegate = self;
        _nameTextfield.leftViewMode = UITextFieldViewModeAlways;
        UIView * leftView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 15, 50)];
        _nameTextfield.leftView = leftView;
        _nameTextfield.enabled = NO;
        
    }
    return _nameTextfield;
}

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

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

- (UITextField *)mobileTextfield{
    if (!_mobileTextfield) {
        _mobileTextfield = [[UITextField alloc] init];
        _mobileTextfield.textColor = UIColor.whiteColor;
        _mobileTextfield.borderStyle = UITextBorderStyleNone;
        _mobileTextfield.layer.borderWidth = 1.f;
        _mobileTextfield.layer.borderColor = UIColor.lightGrayColor.CGColor;
        _mobileTextfield.layer.cornerRadius = 5.f;
        _mobileTextfield.delegate = self;
        _mobileTextfield.keyboardType = UIKeyboardTypePhonePad;
        _mobileTextfield.leftViewMode = UITextFieldViewModeAlways;
        UIView * leftView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 15, 50)];
        _mobileTextfield.leftView = leftView;
    }
    return _mobileTextfield;
}

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

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

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

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