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

#import <Foundation/Foundation.h>
#import "GroupEditController.h"
#import "GroupNetApi.h"
#import "GroupListCell.h"
#import "FriendNetApi.h"
#import "GWebSocket.h"
#import "UDManager.h"
#import "config.h"


@interface GroupEditController()<UITableViewDelegate,UITableViewDataSource,GroupListCellDelegate>

@property (weak, nonatomic) IBOutlet UILabel *titleLb;
@property (weak, nonatomic) IBOutlet UITableView *tableView;



@property (strong, nonatomic) NSArray *dataList;
@property (strong, nonatomic) NSArray *groupUserList;
@property (strong,nonatomic) NSString *userId;

@end


@implementation GroupEditController

-(void)viewDidLoad{
    [super viewDidLoad];
    [self.navigationController setNavigationBarHidden:YES animated:NO];
    if(self.editType==1){
        _titleLb.text = NSLocalizedString(@"EGroupCtr-rqtitle", @"入群审核");
    }
    if (self.editType==2) {
        _titleLb.text = NSLocalizedString(@"EGroupCtr-qunzhuanr", @"转让群");
    }
    if (self.editType==3) {
        _titleLb.text = NSLocalizedString(@"EGroupCtr-yaoqingrq", @"邀请加入群");
    }
    if (self.editType==4) {
        _titleLb.text = NSLocalizedString(@"EGroupCtr-tichuq", @"踢出群");
    }
    
    NSDictionary *userinfo = [UDManager.shareInstance getDDManager:dkuserinfo];
    NSLog(@"userinfo:%@",userinfo);
    _userId = userinfo[@"id"];
    
    [self initFrame];
    [self initData];
}
- (IBAction)gotoback:(id)sender {
    [self dismissViewControllerAnimated:YES completion:nil];
}



-(void)initFrame{
    [_tableView registerClass:[GroupListCell class] forCellReuseIdentifier:@"cellT"];
    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    _tableView.backgroundColor = [UIColor clearColor];
    _tableView.delegate=self;
    _tableView.dataSource=self;
}

-(void)initData{
    if(self.editType==1){
        [self getshenheList];
    }
    else if(self.editType==2){
        [self getGroupUserList];
    }
    else if(self.editType==3){
        [self getGroupUserList];
    }
    else if(self.editType==4){
        [self getGroupUserList];
    }
}


#pragma mark 获取待审核入群人员
-(void)getshenheList{
    [GroupNetApi getshenheList:self.groupId succ:^(int code, NSDictionary * res) {
        NSLog(@"res:%@",res);
        self.dataList = res[@"data"];
        [self->_tableView reloadData];
    } fail:^(NSError * _Nonnull error) {
        
    }];
}

#pragma mark 获取群成员
-(void)getGroupUserList{
    [GroupNetApi getGroupUserList:self.groupId succ:^(int code, NSDictionary * res) {
        if(self.editType == 3){
            self.groupUserList = res[@"data"];
            [self getFriendList];
        }
        else{
            self.dataList = res[@"data"];
            [self->_tableView reloadData];
        }
    } fail:^(NSError * _Nonnull error) {
        
    }];
}
#pragma mark 获取所有好友
-(void)getFriendList{
    [FriendNetApi getfriends:nil succ:^(int code, NSDictionary * res) {
        self.dataList = res[@"data"];
        //NSLog(@"self.friendlist:%@",self.friendlist);
        if(self.dataList){
            [self dowithFriendList];
        }
    } fail:^(NSError * _Nonnull error) {
        
    }];
}

-(void)dowithFriendList{
    NSMutableArray *array = [[NSMutableArray alloc] init];
    for (NSDictionary *item in self.dataList) {
        NSString *fid = item[@"id"];
        BOOL mark=YES;
        for (NSDictionary *jtem in self.groupUserList) {
            NSString *jid = jtem[@"id"];
            if(fid.intValue == jid.intValue){
                mark=NO;
                break;
            }
        }
        if(mark){
            [array addObject:item];
        }
    }
    NSLog(@"self.groupUserList:%@",self.groupUserList);
    NSLog(@"self.dataList:%@",self.dataList);
    self.dataList = array;
    [self.tableView reloadData];
}

#pragma mark UITableViewDelegate

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

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.dataList.count;
}

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

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    NSDictionary *data=self.dataList[indexPath.row];
    NSLog(@"cellForRowAtIndexPath:%@",data);
    if(data){
        
        GroupListCell *cell =[tableView dequeueReusableCellWithIdentifier:@"cellT" forIndexPath:indexPath];
        if(cell==nil){
            cell=[[GroupListCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cellT"];
        }
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.backgroundColor = [UIColor clearColor];
        [cell fillWithData:data cellType:self.editType];
        cell.delegate = self;
        
        return cell;
    }
    return nil;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
}

-(void)GroupListCellAct:(NSString *)actId act:(NSInteger)state{
    NSLog(@"GroupListCellAct:%@,%ld",actId,(long)state);
    if(self.editType==1){//入群审核
        if(state==1){//同意申请
            [self tongyiruqunshenqing:actId];
        }
        else{//拒绝
            [self jujueruqunshenqing:actId];
        }
    }
    if(self.editType==2){//转让
        [self zhuanrangqun:actId];
    }
    if(self.editType==3){//邀请
        [self yaoqingruqun:actId];
    }
    if(self.editType==4){//踢出
        [self tichuqun:actId];
    }
}


#pragma mark net acttion
//
-(void)tongyiruqunshenqing:(NSString *)userid{
    [GroupNetApi Checkagree:userid succ:^(int code, NSDictionary * res) {
        //发送通知
        NSString *coder = res[@"code"];
        if(coder.intValue==200){
            [self sendNote];
        }
        //更新列表
        [self initData];
    } fail:^(NSError * _Nonnull error) {
        
    }];
}

-(void)jujueruqunshenqing:(NSString *)userid{
    [GroupNetApi Checkrefuse:userid succ:^(int code, NSDictionary * res) {
        //更新列表
        [self initData];
    } fail:^(NSError * _Nonnull error) {
        
    }];
}

-(void)zhuanrangqun:(NSString *)userid{
    // 创建弹框询问
    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 transferGroup:self.groupId userId:userid 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];
}

-(void)yaoqingruqun:(NSString *)userid{
    NSArray *userlds = @[userid];
    //NSString *userlds = [NSString stringWithFormat:@"[%@]",userid];
    NSDictionary *dic = @{
        @"userIds":userlds,
        @"groupId":self.groupId
    };
    [GroupNetApi addUsertoGroup:dic groupId:nil succ:^(int code, NSDictionary * res) {
        NSLog(@"res%@",res);
        NSString *coder =res[@"code"];
        if(coder.intValue==200){
            NSMutableArray *array = [[NSMutableArray alloc] init];
            for (NSDictionary *item in self.dataList) {
                NSString *fid = item[@"id"];
                if(userid.intValue!=fid.intValue){
                    [array addObject:item];
                }
            }
            self.dataList = array;
            [self.tableView reloadData];
        }
    } fail:^(NSError * _Nonnull error) {
        NSLog(@"error:%@",error);
    }];
}

-(void)tichuqun:(NSString *)userid{
    // 创建弹框询问
    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 getoutUserGroup:self.groupId userId:userid succ:^(int code, NSDictionary * res) {
            [self initData];
        } fail:^(NSError * _Nonnull error) {
            
        }];
    }];
    [alert addAction:cancelAction];
    [alert addAction:okAction];
    // 显示弹框
    [self presentViewController:alert animated:YES completion:nil];
}


-(void)sendNote{
   
    NSDate *now = [NSDate date];
    NSTimeInterval trt = [now timeIntervalSince1970];
    NSInteger time = trt*1000;
    NSString *strtime = [NSString stringWithFormat:@"%ld",(long)time];
   
    NSString *content = @"有新用户入群";
    NSDictionary *callMsg = @{
        @"code":SendCode_MESSAGE,
        @"message": @{
            @"chatId":self.groupId,
            @"fromId":self.userId,
            @"type":@"1",
            @"mine":@"ture",
            @"content":content,
            @"timestamp":strtime,
            @"messageType":MessageType_event
        }
    };
    NSError *error;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:callMsg options:0 error:&error];
    if (!jsonData) {
        NSLog(@"Got an error: %@", error);
    } else {
        NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
        NSLog(@"%@", jsonString); // 输出: {"name":"John","age":25}
        [GWebSocket.shareInstance sendMsg:jsonString];
    }
}

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