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

#import <Foundation/Foundation.h>
#import "GroupController.h"
#import "GroupNetApi.h"
#import <SDWebImage/UIImageView+WebCache.h>
#import "ChatController.h"
#import "ChatListStore.h"
#import "config.h"
#import "UDManager.h"
#import "GroupEditController.h"
#import "GroupGonggaoController.h"
#import "ChatHistoryController.h"
#import "NewGroupController.h"
#import "FriendNetApi.h"

@interface GroupController()<UITableViewDelegate,UITableViewDataSource,UICollectionViewDelegate,UICollectionViewDataSource>
@property (weak, nonatomic) IBOutlet UICollectionView *collView;
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (weak, nonatomic) IBOutlet UIScrollView *ctScrollView;
@property (weak, nonatomic) IBOutlet UILabel *bartitleLb;
@property (weak, nonatomic) IBOutlet UIButton *rightBt;


@property (nonatomic,strong) NSMutableArray *cellDatas;
@property (nonatomic,strong) NSMutableArray *collDatas;
@property (nonatomic,strong) NSString *master;
@property (nonatomic) BOOL ismaster;
@property (nonatomic) BOOL reloadMsg;
@property (nonatomic, strong) NSDictionary * noDisturbDict;
@end

@implementation GroupController

-(void)viewDidLoad{
    [super viewDidLoad];
    [self.navigationController setNavigationBarHidden:YES animated:NO];
    _bartitleLb.text = @"";
    _reloadMsg=NO;
    _cellDatas = [[NSMutableArray alloc] init];
    _collDatas = [[NSMutableArray alloc] init];
    _rightBt.alpha = 0;
    if(self.groupMsg){
        [self initData];
        [self getNoDiturbSettingData];
    }
    else{
        if(self.groupId){
            [self getNetGroupMsg];
        }
    }
    [self initSubView];
}

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:YES];
    if(_reloadMsg){
        [self getNetGroupMsg];
    }
}

-(void)viewDidDisappear:(BOOL)animated{
    [super viewDidDisappear:YES];
    _reloadMsg=YES;
}


-(void)initData{
    
    _ismaster=NO;
    
    if (self.groupMsg) {
        _master = self.groupMsg[@"master"]?:@"";
        _groupId =self.groupMsg[@"id"];
        NSDictionary *userInfo = [UDManager.shareInstance getDDManager:dkuserinfo];
        if ([_master isEqualToString:userInfo[@"id"]]) {
            _ismaster=YES;
            _rightBt.alpha = 1;
        }
    }
    _bartitleLb.text = self.groupMsg[@"name"];
    
    NSDictionary *d1 =@{
        @"name":@"GroupCtr-xiaoximdr",
        @"image":@"noDisturb_chat_icon",
    };
    NSDictionary *d2 =@{
        @"name":@"GroupCtr-ruquanshe",
        @"image":@"check_group_icon",
    };
    NSDictionary *d3 =@{
        @"name":@"GroupCtr-zhuanrangq",
        @"image":@"transfer_group_icon",
    };
    NSDictionary *d4 =@{
        @"name":@"GroupCtr-liaotianjl",
        @"image":@"record_chat_icon",
    };
    NSDictionary *d5 =@{
        @"name":@"GroupCtr-gonggao",
        @"image":@"announce_group_icon",
    };
    NSDictionary *d6 =@{
        @"name":@"GroupCtr-liaotian",
        @"image":@"wzhuxiaozz",
    };
    
    NSString *d7name = @"GroupCtr-tuichuql";
    if(_ismaster){
        d7name = @"GroupCtr-jiesanquz";
    }
    
    NSDictionary *d7 =@{
        @"name":d7name,
        @"image":@"wzhuxiaozz",
    };
    
    
    [_cellDatas removeAllObjects];
    
    if(_ismaster){
        [_cellDatas addObject:d2];
        [_cellDatas addObject:d3];
    }
    [_cellDatas addObject:d4];
    [_cellDatas addObject:d5];
    [_cellDatas addObject:d1];
    [_cellDatas addObject:d6];
    [_cellDatas addObject:d7];
    
    
    [self getGroupUsers];
}

-(void)getNetGroupMsg{
    [GroupNetApi getGroupInfo:self.groupId succ:^(int code, NSDictionary * res) {
        NSLog(@"res:%@",res);
        self.groupMsg = [self replaceNullsWithEmptyStringInDictionary:res[@"data"]];
        [self initData];
        [self getNoDiturbSettingData];
        [self.tableView reloadData];
    } fail:^(NSError * _Nonnull error) {
        
    }];
}

-(void)getNoDiturbSettingData{
    [FriendNetApi getNoDisturbSetting:self.groupMsg[@"id"] succ:^(int code, NSDictionary * _Nullable result) {
        NSLog(@"noDisturbSetting:-----%@",result);
        NSArray * dataArray = result[@"data"];
        if (dataArray.count!=0) {
            self.noDisturbDict = dataArray[0];
        }
        [self.tableView reloadData];
    } fail:^(NSError * _Nonnull error) {
        
    }];
}

- (void)saveNoDisturbSetting{
    NSDictionary * param = @{
        @"userId":self.groupMsg[@"id"],
        @"chatId":self.groupMsg[@"id"]
    };
    [FriendNetApi saveNoDisturbSetting:param succ:^(int code, NSDictionary * _Nullable result) {
        [MBProgressHUD showWithText:result[@"msg"]];
    } fail:^(NSError * _Nonnull error) {
        
    }];
}

- (void)cancelNoDisturbSetting{
    [FriendNetApi cancelNoDisturbSettingWithUserId:self.groupMsg[@"id"] chatId:self.groupMsg[@"id"] succ:^(int code, NSDictionary * _Nullable result) {
        [MBProgressHUD showWithText:result[@"msg"]];
    } fail:^(NSError * _Nonnull error) {
        
    }];
}

-(void)initSubView{
    [_tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"cellT"];
    [_tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"cellTT"];
    [_tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"cellTT3"];
    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    _tableView.backgroundColor = [UIColor clearColor];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    _tableView.scrollEnabled = NO;
    
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    layout.scrollDirection = UICollectionViewScrollDirectionVertical; // 设置垂直流布局
    CGFloat width = _collView.frame.size.width;
    width=(width-20)/3;
    layout.itemSize = CGSizeMake(width, width); // 设置每个item的大小
    layout.minimumInteritemSpacing = 5; // 设置单元格之间的间距
    [_collView setCollectionViewLayout:layout];
    [_collView registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:@"collT"];
    [_collView registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:@"collTT"];
    _collView.dataSource = self;
    _collView.delegate = self;
    _collView.backgroundColor = [UIColor clearColor];
    _ctScrollView.showsVerticalScrollIndicator =NO;
    _ctScrollView.backgroundColor = [UIColor clearColor];
       
}

-(void)resetframe{
    NSLog(@"_ismaster");
    CGFloat tableH = _cellDatas.count*62;
    NSInteger row =_collDatas.count/3;
    
    if(_ismaster){
        NSLog(@"_ismaster11-----");
        row =(_collDatas.count+2)/3;
        if((_collDatas.count+2)>row*3) {
            row=row+1;
        }
    }
    else{
        NSString *openInvite = self.groupMsg[@"openInvite"];
        if(openInvite.intValue==1){
            row =(_collDatas.count+1)/3;
            if((_collDatas.count+1)>row*3) {
                row=row+1;
            }
        }
        else{
            row =_collDatas.count/3;
            if(_collDatas.count>row*3) {
                row=row+1;
            }
        }
    }
    
    CGFloat width = _collView.frame.size.width;
    width=(width-20)/3;
    
    CGFloat collVH = row*(width+10);
    
    CGRect r = _collView.frame;
    r.origin.x =0.0f;
    r.origin.y = 0.0f;
    r.size.height = collVH;
    _collView.frame = r;
    
    CGRect t = _tableView.frame;
    t.origin.x =0.0f;
    t.origin.y = collVH +10.0f;
    t.size.height = tableH;
    _tableView.frame = t;
    
    _ctScrollView.contentSize = CGSizeMake(_ctScrollView.frame.size.width, tableH+collVH+20);
    [_collView reloadData];
    [_tableView reloadData];
}

- (IBAction)gotoBack:(id)sender {
    [self dismissViewControllerAnimated:YES completion:nil];
}
- (IBAction)rightBt:(id)sender {
    UIStoryboard *board = [UIStoryboard storyboardWithName:@"Main" bundle:[NSBundle mainBundle]];
    NewGroupController *groupctr = [board instantiateViewControllerWithIdentifier:@"NewGroupController"];
    groupctr.groupMsg = self.groupMsg;
    UINavigationController *uiNavC = [[UINavigationController alloc] initWithRootViewController:groupctr];
    uiNavC.modalPresentationStyle = UIModalPresentationFullScreen;
    [self presentViewController :uiNavC animated:YES completion:nil];
}

- (void)switchAction:(id)sender {
    UISwitch *switchButton = (UISwitch*)sender;
    BOOL isButtonOn = [switchButton isOn];
    if (isButtonOn) {
        // 处理开关打开的情况
        NSLog(@"isButtonOn");
        [self saveNoDisturbSetting];
    } else {
        // 处理开关关闭的情况
        NSLog(@"isButtonOff");
        [self cancelNoDisturbSetting];
    }
}

#pragma mark UICollectionViewDelegate

-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    return 1;
}

-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    if(_ismaster){
        return self.collDatas.count +2;
    }
    else{
        NSString *openInvite = self.groupMsg[@"openInvite"];
        if(openInvite.intValue==1){
            return self.collDatas.count +1;
        }
        else{
            return self.collDatas.count;
        }
        
    }
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    
    // 配置cell的内容
    if(indexPath.row==self.collDatas.count){
        UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"collTT" forIndexPath:indexPath];
        CGFloat width = cell.frame.size.width;
        UIImageView *img = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"jiaqun"]];
        [cell addSubview:img];
        img.contentMode = UIViewContentModeScaleAspectFill;
        img.frame = CGRectMake(20, 0, width-40, width-40);
        img.layer.cornerRadius = (width-40)/2;
        img.layer.masksToBounds = YES;
        img.backgroundColor=[UIColor lightGrayColor];
        cell.backgroundColor=[UIColor clearColor];
        return cell;
    }
    else if(indexPath.row==self.collDatas.count+1){
        UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"collTT" forIndexPath:indexPath];
        CGFloat width = cell.frame.size.width;
        UIImageView *img = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"tichuqun"]];
        [cell addSubview:img];
        img.contentMode = UIViewContentModeScaleAspectFill;
        img.frame = CGRectMake(20, 0, width-40, width-40);
        img.layer.cornerRadius = (width-40)/2;
        img.layer.masksToBounds = YES;
        img.backgroundColor=[UIColor lightGrayColor];
        cell.backgroundColor=[UIColor clearColor];
        return cell;
    }
    else{
       
        UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"collT" forIndexPath:indexPath];
        
        NSArray *array = cell.contentView.subviews;
        for (id sbv in array) {
            [sbv removeFromSuperview];
        }
        NSDictionary *dic = self.collDatas[indexPath.row];
        CGFloat width = cell.frame.size.width;
        UIImageView *img = [[UIImageView alloc] init];
        [cell.contentView addSubview:img];
        [img sd_setImageWithURL:[NSURL URLWithString:dic[@"avatar"]] placeholderImage:[UIImage imageNamed:@"Avatar"]];
        img.contentMode = UIViewContentModeScaleAspectFill;
        img.frame = CGRectMake(20, 0, width-40, width-40);
        img.layer.cornerRadius = (width-40)/2;
        img.layer.masksToBounds = YES;
        img.backgroundColor=[UIColor lightGrayColor];
        
        UILabel *name = [[UILabel alloc] init];
        name.text = dic[@"name"];
        [cell.contentView addSubview:name];
        name.frame = CGRectMake(0, width-40, width, 30.0f);
        name.textAlignment = NSTextAlignmentCenter;
        if([_master isEqualToString:dic[@"id"]]){
            name.textColor = globalColor(GCTypeOrangeR);
            name.font = [UIFont systemFontOfSize:15.0f];
        }
        else{
            name.textColor = [UIColor whiteColor];
            name.font = [UIFont systemFontOfSize:14.0f];
        }
        cell.backgroundColor=[UIColor clearColor];
        return cell;
    }
    return nil;
}

-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    if(indexPath.row==self.collDatas.count){//邀请加入群
        UIStoryboard *board = [UIStoryboard storyboardWithName:@"groupstory" bundle:[NSBundle mainBundle]];
        GroupEditController *chatctr = [board instantiateViewControllerWithIdentifier:@"GroupEditController"];
        UINavigationController *uiNavC = [[UINavigationController alloc] initWithRootViewController:chatctr];
        uiNavC.modalPresentationStyle = UIModalPresentationFullScreen;
        chatctr.editType = 3;
        chatctr.groupId = self.groupMsg[@"id"];
        [self presentViewController :uiNavC animated:YES completion:nil];
        
    }else if(indexPath.row==self.collDatas.count+1){//踢出群
        UIStoryboard *board = [UIStoryboard storyboardWithName:@"groupstory" bundle:[NSBundle mainBundle]];
        GroupEditController *chatctr = [board instantiateViewControllerWithIdentifier:@"GroupEditController"];
        UINavigationController *uiNavC = [[UINavigationController alloc] initWithRootViewController:chatctr];
        uiNavC.modalPresentationStyle = UIModalPresentationFullScreen;
        chatctr.editType = 4;
        chatctr.groupId = self.groupMsg[@"id"];
        [self presentViewController :uiNavC animated:YES completion:nil];
    }
    
    NSLog(@"");
}


#pragma mark UITableViewDelegate

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    NSInteger section =indexPath.section;
    NSDictionary *time =_cellDatas[section];
    NSString *cellT =@"cellT";
    if(section>_cellDatas.count-3){
        cellT =@"cellTT";
        UITableViewCell *cell =[tableView dequeueReusableCellWithIdentifier:cellT forIndexPath:indexPath];
        if(cell==nil){
            cell=[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellT];
        }
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.backgroundColor = [UIColor clearColor];
        cell.contentView.layer.borderWidth = 0.5f;
        cell.contentView.layer.borderColor = [UIColor lightGrayColor].CGColor; //globalColor(GCTypeGreen);
        cell.contentView.layer.cornerRadius = 8.0f; // 可选，设置圆角
        if(section==_cellDatas.count-1){
            cell.contentView.backgroundColor = globalColor(GCTypeOrangeR);
        }
        else{
            cell.contentView.backgroundColor = globalColor(GCTypeGreen);
            
        }
        
        cell.textLabel.text =NSLocalizedString(time[@"name"], @"");
        cell.textLabel.textAlignment = NSTextAlignmentCenter;
        
        return cell;
    }
    else if(indexPath.section == self.cellDatas.count-3){
        cellT =@"cellTT3";
        UITableViewCell *cell =[tableView dequeueReusableCellWithIdentifier:cellT forIndexPath:indexPath];
        if(cell==nil){
            cell=[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellT];
        }
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.backgroundColor = [UIColor clearColor];
        NSString *title = NSLocalizedString(time[@"name"], @"");
        
        cell.imageView.image = [UIImage imageNamed:time[@"image"]];
        cell.textLabel.text =title;
        cell.textLabel.textColor = [UIColor whiteColor];
        CGRect ctfrm = cell.contentView.frame;
        UISwitch * stateSwitch = [[UISwitch alloc] initWithFrame:CGRectMake(ctfrm.size.width-66, 10, 20, 10)];
        stateSwitch.onImage = kImageMake(@"switch_on");
        stateSwitch.offImage = kImageMake(@"switch_off");
        
        if (self.noDisturbDict && [self.noDisturbDict jk_hasKey:@"id"]) {
            [stateSwitch setOn:YES];
        }else{
            [stateSwitch setOn:NO];
        }
        [stateSwitch addTarget:self action:@selector(switchAction:) forControlEvents:UIControlEventValueChanged];
        [cell.contentView addSubview:stateSwitch];
        cell.contentView.layer.borderWidth = 0.5f;
        cell.contentView.layer.borderColor = [UIColor lightGrayColor].CGColor; //globalColor(GCTypeGreen);
        cell.contentView.layer.cornerRadius = 8.0f; // 可选，设置圆角
        return cell;
    }
    else{
        UITableViewCell *cell =[tableView dequeueReusableCellWithIdentifier:cellT forIndexPath:indexPath];
        if(cell==nil){
            cell=[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellT];
        }
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.backgroundColor = [UIColor clearColor];
        NSString *title = NSLocalizedString(time[@"name"], @"");
        
        cell.imageView.image = [UIImage imageNamed:time[@"image"]];
        cell.textLabel.text =title;
        cell.textLabel.textColor = [UIColor whiteColor];
        CGRect ctfrm = cell.contentView.frame;
        UIImageView *right = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"arrow-right"]];
        right.frame = CGRectMake(ctfrm.size.width-30, 21, 20, 20);
        [cell.contentView addSubview:right];
        cell.contentView.layer.borderWidth = 0.5f;
        cell.contentView.layer.borderColor = [UIColor lightGrayColor].CGColor; //globalColor(GCTypeGreen);
        cell.contentView.layer.cornerRadius = 8.0f; // 可选，设置圆角
        return cell;
    }
    

}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if(_ismaster){//群主
        if(indexPath.section == 0){
            [self gotoRuqunshenhe];
        }
        if(indexPath.section == 1){
            [self zhuanrangqun];
        }
        if(indexPath.section == 2){
            [self gotoLiaotianjilu];
        }
        if(indexPath.section == 3){
            [self gotoGonggao];
        }
        
        if(indexPath.section == 5){
            [self gotoChart];
        }
        if(indexPath.section == 6){
            [self jiesanqun];
        }
    }
    else{//非群主
        if(indexPath.section == 0){
            [self gotoLiaotianjilu];
        }
        if(indexPath.section == 1){
            [self gotoGonggao];
        }
        
        if(indexPath.section == 3){
            [self gotoChart];
        }
        if(indexPath.section == 4){
            [self tuichuqun];
        }
    }
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return 1;
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return _cellDatas.count;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 52.0;
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    CGFloat height =10.0;
    if(section==0){
        height =0.0;
    }
    return height;
}

-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    CGFloat height =10.0;
    if(section==0){
        height =0.0;
    }
    UIView *view =[[UIView alloc] initWithFrame:CGRectMake(0, 0, 100, height)];
    view.backgroundColor = [UIColor clearColor];
    return view;
}


-(void)getGroupUsers{
    NSLog(@"self.groupMsg:%@",self.groupMsg);
    if (self.groupMsg) {
        [GroupNetApi getGroupUserList:self.groupMsg[@"id"] succ:^(int code, NSDictionary *res) {
            NSLog(@"res:%@",res);
            self.collDatas = [NSMutableArray arrayWithArray:[self replaceNullsWithEmptyStringInArray:res[@"data"]]];
            [self resetframe];
        } fail:^(NSError * _Nonnull error) {
            NSLog(@"errer");
        }];
    }
}

#pragma mark 入群审核
-(void)gotoRuqunshenhe{
    UIStoryboard *board = [UIStoryboard storyboardWithName:@"groupstory" bundle:[NSBundle mainBundle]];
    GroupEditController *chatctr = [board instantiateViewControllerWithIdentifier:@"GroupEditController"];
    UINavigationController *uiNavC = [[UINavigationController alloc] initWithRootViewController:chatctr];
    uiNavC.modalPresentationStyle = UIModalPresentationFullScreen;
    chatctr.editType = 1;
    chatctr.groupId = self.groupMsg[@"id"];
    [self presentViewController :uiNavC animated:YES completion:nil];
}
#pragma mark 转让群
-(void)zhuanrangqun{
    UIStoryboard *board = [UIStoryboard storyboardWithName:@"groupstory" bundle:[NSBundle mainBundle]];
    GroupEditController *chatctr = [board instantiateViewControllerWithIdentifier:@"GroupEditController"];
    UINavigationController *uiNavC = [[UINavigationController alloc] initWithRootViewController:chatctr];
    uiNavC.modalPresentationStyle = UIModalPresentationFullScreen;
    chatctr.editType = 2;
    chatctr.groupId = self.groupMsg[@"id"];
    [self presentViewController :uiNavC animated:YES completion:nil];
}

#pragma mark 聊天记录
-(void)gotoLiaotianjilu{
    UIStoryboard *board = [UIStoryboard storyboardWithName:@"ChatHistory" bundle:[NSBundle mainBundle]];
    ChatHistoryController *chatctr = [board instantiateViewControllerWithIdentifier:@"ChatHistoryController"];
    UINavigationController *uiNavC = [[UINavigationController alloc] initWithRootViewController:chatctr];
    uiNavC.modalPresentationStyle = UIModalPresentationFullScreen;
    chatctr.chatId = self.groupMsg[@"id"];
    chatctr.type = 1;
    chatctr.titlename = self.groupMsg[@"name"];
    chatctr.avatar = self.groupMsg[@"avatar"];
    [self presentViewController :uiNavC animated:YES completion:nil];
}
#pragma mark 公告
-(void)gotoGonggao{
    UIStoryboard *board = [UIStoryboard storyboardWithName:@"groupstory" bundle:[NSBundle mainBundle]];
    GroupGonggaoController *chatctr = [board instantiateViewControllerWithIdentifier:@"GroupGonggaoController"];
    UINavigationController *uiNavC = [[UINavigationController alloc] initWithRootViewController:chatctr];
    uiNavC.modalPresentationStyle = UIModalPresentationFullScreen;
    chatctr.groupId = self.groupMsg[@"id"];
    chatctr.gonggao =self.groupMsg[@"announcement"];
    if(_ismaster){
        chatctr.editType = 1;
    }
    else{
        chatctr.editType = 2;
    }
    
    [self presentViewController :uiNavC animated:YES completion:nil];
}

#pragma mark 消息免打扰
-(void)changeXiaoximdr{
    
}


#pragma mark 聊天
-(void)gotoChart{
    UIStoryboard *board = [UIStoryboard storyboardWithName:@"Main" bundle:[NSBundle mainBundle]];
    
    ChatController *chatctr = [board instantiateViewControllerWithIdentifier:@"ChatController"];
    
    UINavigationController *uiNavC = [[UINavigationController alloc] initWithRootViewController:chatctr];
    
    uiNavC.modalPresentationStyle = UIModalPresentationFullScreen;
    
    chatctr.chatId = self.groupMsg[@"id"];
    chatctr.type = 1;
    ChatListStore.shareInstance.chatId =self.groupMsg[@"id"];
    chatctr.titlename = self.groupMsg[@"name"];
    chatctr.avatar = self.groupMsg[@"avatar"];
    [self presentViewController :uiNavC animated:YES completion:nil];
}

#pragma mark 退出群
-(void)tuichuqun{
    // 创建弹框询问
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示"
                                                                 message:@"是否确认退出群？"
                                                          preferredStyle:UIAlertControllerStyleAlert];
    // 创建取消按钮和确定按钮，并添加到弹框中
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
        NSLog(@"用户点击了取消");
    }];
    UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
        NSLog(@"用户点击了确定");
        [GroupNetApi exitGroup:self.groupId succ:^(int code, NSDictionary * res) {
            NSString *coder = res[@"code"];
            if(coder.intValue==200){
                [self dismissViewControllerAnimated:YES completion:nil];
            }
        } fail:^(NSError * _Nonnull error) {
            
        }];
    }];
    [alert addAction:cancelAction];
    [alert addAction:okAction];
    // 显示弹框
    [self presentViewController:alert animated:YES completion:nil];
}

#pragma mark 解散群
-(void)jiesanqun{
    // 创建弹框询问
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示"
                                                                 message:@"是否确认解散群？"
                                                          preferredStyle:UIAlertControllerStyleAlert];
    // 创建取消按钮和确定按钮，并添加到弹框中
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
        NSLog(@"用户点击了取消");
    }];
    UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
        NSLog(@"用户点击了确定");
        [GroupNetApi deleteGroup:self.groupId succ:^(int code, NSDictionary * res) {
            NSString *coder = res[@"code"];
            if(coder.intValue==200){
                [self dismissViewControllerAnimated:YES completion:nil];
            }
        } fail:^(NSError * _Nonnull error) {
            
        }];
    }];
    [alert addAction:cancelAction];
    [alert addAction:okAction];
    // 显示弹框
    [self presentViewController:alert animated:YES completion:nil];
}

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

#pragma mark 工具
// 递归替换字典中的 NSNull 为 @""
- (NSDictionary *)replaceNullsWithEmptyStringInDictionary:(NSDictionary *)dictionary {
    NSMutableDictionary *mutableDict = [NSMutableDictionary dictionaryWithDictionary:dictionary];
    
    for (id key in [mutableDict allKeys]) {
        id value = [mutableDict objectForKey:key];
        
        if ([value isKindOfClass:[NSNull class]]) {
            [mutableDict setObject:@"" forKey:key];
        } else if ([value isKindOfClass:[NSDictionary class]]) {
            // 递归处理子字典
            [mutableDict setObject:[self replaceNullsWithEmptyStringInDictionary:value] forKey:key];
        } else if ([value isKindOfClass:[NSArray class]]) {
            // 递归处理数组
            [mutableDict setObject:[self replaceNullsWithEmptyStringInArray:value] forKey:key];
        }
    }
    
    return [NSDictionary dictionaryWithDictionary:mutableDict];
}

// 递归替换数组中的 NSNull 为 @""
- (NSArray *)replaceNullsWithEmptyStringInArray:(NSArray *)array {
    NSMutableArray *mutableArray = [NSMutableArray arrayWithArray:array];
    
    for (NSInteger i = 0; i < [mutableArray count]; i++) {
        id value = [mutableArray objectAtIndex:i];
        
        if ([value isKindOfClass:[NSNull class]]) {
            [mutableArray replaceObjectAtIndex:i withObject:@""];
        } else if ([value isKindOfClass:[NSDictionary class]]) {
            // 递归处理子字典
            [mutableArray replaceObjectAtIndex:i withObject:[self replaceNullsWithEmptyStringInDictionary:value]];
        } else if ([value isKindOfClass:[NSArray class]]) {
            // 递归处理子数组
            [mutableArray replaceObjectAtIndex:i withObject:[self replaceNullsWithEmptyStringInArray:value]];
        }
    }
    
    return [NSArray arrayWithArray:mutableArray];
}

@end
