//
//  NewGroupController.m
//  AIIM
//
//  Created by gan on 2025/4/21.
//

#import <Foundation/Foundation.h>
#import "NewGroupController.h"
#import "config.h"
#import "GroupNetApi.h"
#import <SDWebImage/UIImageView+WebCache.h>

@interface NewGroupController()<UIImagePickerControllerDelegate,UINavigationControllerDelegate>
@property (weak, nonatomic) IBOutlet UIImageView *avatar;
@property (weak, nonatomic) IBOutlet UITextField *inputName;
@property (weak, nonatomic) IBOutlet UITableViewCell *yaoqingCell;
@property (weak, nonatomic) IBOutlet UILabel *titleLb;

@property (weak, nonatomic) IBOutlet UITableViewCell *shenheCell;

@property (weak, nonatomic) IBOutlet UITableViewCell *jinyanCell;
@property (weak, nonatomic) IBOutlet UITableViewCell *jiahaoyCell;
@property (weak, nonatomic) IBOutlet UIButton *saveBt;

@property (weak, nonatomic) IBOutlet UISwitch *yaoqingS;
@property (weak, nonatomic) IBOutlet UISwitch *shenheS;

@property (weak, nonatomic) IBOutlet UISwitch *jinyanS;
@property (weak, nonatomic) IBOutlet UISwitch *jinjiaS;


@property (nonatomic,strong) NSString *avatarStr;

@property (nonatomic,strong) NSString *yaoqing;
@property (nonatomic,strong) NSString *jinyan;
@property (nonatomic,strong) NSString *jinjia;
@property (nonatomic,strong) NSString *shenhe;



@end

@implementation NewGroupController

-(void)viewDidLoad{
    [super viewDidLoad];
    [self.navigationController setNavigationBarHidden:YES animated:NO];
    _titleLb.text = NSLocalizedString(@"group-addNew", @"");
    // 创建一个点击手势
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(dismissKeyboard)];
    // 将手势添加到主视图上
    [self.view addGestureRecognizer:tap];
    _yaoqing=@"1";
    _jinyan=@"0";
    _jinjia=@"0";
    _shenhe=@"1";
    [self initSubview];
    [self initGData];
}

-(void)dismissKeyboard{
    NSLog(@"dismissKeyboard");
    [self.view endEditing:YES];
}
- (IBAction)gotoback:(id)sender {
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (IBAction)yaoqingC:(id)sender {
    UISwitch *switchButton = (UISwitch*)sender;
    BOOL isButtonOn = [switchButton isOn];
    if(isButtonOn){
        _yaoqing = @"1";
    }
    else{
        _yaoqing = @"0";
    }
}

- (IBAction)shenheC:(id)sender {
    UISwitch *switchButton = (UISwitch*)sender;
    BOOL isButtonOn = [switchButton isOn];
    if(isButtonOn){
        _shenhe = @"1";
    }
    else{
        _shenhe = @"0";
    }
}

- (IBAction)jinyanC:(id)sender {
    UISwitch *switchButton = (UISwitch*)sender;
    BOOL isButtonOn = [switchButton isOn];
    if(isButtonOn){
        _jinyan = @"1";
    }
    else{
        _jinyan = @"0";
    }
}

- (IBAction)jinjiaC:(id)sender {
    UISwitch *switchButton = (UISwitch*)sender;
    BOOL isButtonOn = [switchButton isOn];
    if(isButtonOn){
        _jinjia = @"1";
    }
    else{
        _jinjia = @"0";
    }
}

- (IBAction)selectImg:(id)sender {
    [self openImagePicker];
}


- (IBAction)saveAct:(id)sender {
    [self addnewGroup];
}

-(void)initSubview{
    _yaoqingCell.contentView.layer.borderWidth = 0.5f;
    _yaoqingCell.contentView.layer.borderColor = [UIColor lightGrayColor].CGColor; //globalColor(GCTypeGreen);
    _yaoqingCell.contentView.layer.cornerRadius = 8.0f; // 可选，设置圆角
    _yaoqingCell.textLabel.text =NSLocalizedString(@"NGroupCtr-kaiqiyaoq", @"开启邀请");
    _yaoqingCell.textLabel.textColor = [UIColor whiteColor];
    [_yaoqingS setOn:YES];
    
    
    [_saveBt setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [_saveBt setBackgroundColor:globalColor(GCTypeGreen)];
    _saveBt.layer.cornerRadius = 8;
    _saveBt.layer.masksToBounds = YES; // 防止子视图超出圆角边界
    
    _shenheCell.contentView.layer.borderWidth = 0.5f;
    _shenheCell.contentView.layer.borderColor = [UIColor lightGrayColor].CGColor;
    _shenheCell.contentView.layer.cornerRadius = 8.0f; // 可选，设置圆角
    _shenheCell.textLabel.text =NSLocalizedString(@"NGroupCtr-ruqunxsh", @"入群需审核");
    _shenheCell.textLabel.textColor = [UIColor whiteColor];
    [_shenheS setOn:YES];
    
    _jinyanCell.contentView.layer.borderWidth = 0.5f;
    _jinyanCell.contentView.layer.borderColor = [UIColor lightGrayColor].CGColor; //globalColor(GCTypeGreen);
    _jinyanCell.contentView.layer.cornerRadius = 8.0f; // 可选，设置圆角
    _jinyanCell.textLabel.text =NSLocalizedString(@"NGroupCtr-quantijy", @"全体禁言");
    _jinyanCell.textLabel.textColor = [UIColor whiteColor];
    [_jinyanS setOn:NO];
    
    _jiahaoyCell.contentView.layer.borderWidth = 0.5f;
    _jiahaoyCell.contentView.layer.borderColor = [UIColor lightGrayColor].CGColor; //globalColor(GCTypeGreen);
    _jiahaoyCell.contentView.layer.cornerRadius = 8.0f; // 可选，设置圆角
    _jiahaoyCell.textLabel.text =NSLocalizedString(@"NGroupCtr-jinjiahy", @"禁加好友");
    _jiahaoyCell.textLabel.textColor = [UIColor whiteColor];
    [_jinjiaS setOn:NO];
   
}

-(void)initGData{
    _avatarStr = @"";
    if(self.groupMsg){
        _avatarStr = self.groupMsg[@"avatar"];
        NSString *temp = self.groupMsg[@"name"];
        _inputName.text = temp;
        temp = self.groupMsg[@"openInvite"];
        _yaoqing=temp;
        if(temp.intValue ==1){
            [_yaoqingS setOn:YES];
        }
        else{
            [_yaoqingS setOn:NO];
        }
        temp = self.groupMsg[@"inviteCheck"];
        _shenhe=temp;
        if(temp.intValue ==1){
            [_shenheS setOn:YES];
        }
        else{
            [_shenheS setOn:NO];
        }
        temp = self.groupMsg[@"prohibition"];
        _jinyan=temp;
        if(temp.intValue ==1){
            [_jinyanS setOn:YES];
        }
        else{
            [_jinyanS setOn:NO];
        }
        temp = self.groupMsg[@"prohibitFriend"];
        _jinjia=temp;
        if(temp.intValue ==1){
            [_jinjiaS setOn:YES];
        }
        else{
            [_jinjiaS setOn:NO];
        }
    }
    [_avatar sd_setImageWithURL:[NSURL URLWithString:_avatarStr] placeholderImage:[UIImage imageNamed:@"Avatar"]];
   
}

/*
   * 添加群组
   * @param name 群名称
   * @param avatar 群头像
   * @param openInvite  是否开放邀请
   * @param inviteCheck 加群是否需要审核
   * @param prohibition 禁言
   * @param prohibitFriend 是否允许加好友
   * @param announcement 群公告
*/

-(void)addnewGroup{
    if(self.groupMsg){
        NSString *groupId = self.groupMsg[@"id"];
        NSDictionary *dic = @{
            @"name":_inputName.text,
            @"avatar":_avatarStr,
            @"openInvite":_yaoqing,
            @"inviteCheck":_shenhe,
            @"prohibition":_jinyan,
            @"prohibitFriend":_jinjia,
        };
        [GroupNetApi updateGroup:dic groupId:groupId succ:^(int code, NSDictionary * res) {
            NSLog(@"res updateGroup:%@",res);
            NSString *codestr = res[@"code"];
            if(codestr.intValue==200){
                [self dismissViewControllerAnimated:YES completion:nil];
            }
        } fail:^(NSError * _Nonnull error) {
            
        }];
    }
    else{
        if(_inputName.text.length>0){
            
            NSDictionary *dic = @{
                @"name":_inputName.text,
                @"avatar":_avatarStr,
                @"openInvite":_yaoqing,
                @"inviteCheck":_shenhe,
                @"prohibition":_jinyan,
                @"prohibitFriend":_jinjia,
                @"announcement":@"",
            };
            [GroupNetApi addNewGroup:dic succ:^(int code, NSDictionary * res) {
                NSLog(@"res addNewGroup:%@",res);
                NSString *codestr = res[@"code"];
                if(codestr.intValue==200){
                    [self dismissViewControllerAnimated:YES completion:nil];
                }
            } fail:^(NSError * _Nonnull error) {
                
            }];
        }
        else{
        }
    }
    
    
}


#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->_avatarStr = res[@"url"];
        [self->_avatar sd_setImageWithURL:[NSURL URLWithString:self->_avatarStr] placeholderImage:[UIImage imageNamed:@"Avatar"]];
    } fail:^(NSError * _Nonnull error) {
        ;
    }];
    
}

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

@end
