//
//  ForwardViewController.m
//  AIIM
//
//  Created by qitewei on 2025/5/10.
//

#import "ForwardViewController.h"

#import "FriendListCell.h"
#import "FriendNetApi.h"
#import "GroupNetApi.h"
#import "ChatListStore.h"
#import "GWebSocket.h"
#import "UDManager.h"

@interface ForwardViewController ()<UITableViewDelegate,UITableViewDataSource>
@property (nonatomic, strong) UIImageView * bgImageView;
@property (nonatomic, strong) UIButton * leftBtn;
@property (nonatomic, strong) UITableView  * tableView;

@property (nonatomic, strong) NSMutableArray * dataArray;
@property (nonatomic, strong) NSMutableArray * groupArray;
@end

@implementation ForwardViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self configUI];
    [self getGroupList];
    [self getFriendlist];
}

- (void)configUI{
    [self setNavigationTitle:@"转发"];
    [self setNavigationBarTransparent:YES];
    [self setNavigationBarBackgroundColor:UIColor.clearColor];
    [self setNavigationTitleColor:UIColor.whiteColor font:SYSBFONT(18)];
    [self addBarButtonWithImage:kImageMake(@"fanhui") position:BarButtonItemPositionLeft action:@selector(backToChat)];
    
    [self.view addSubview:self.bgImageView];
    [self.bgImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.top.bottom.mas_equalTo(0);
    }];
    
    [self.view addSubview:self.tableView];
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.bottom.mas_equalTo(0);
        make.top.mas_equalTo(SCREEN_TOP);
    }];
}

#pragma mark api
- (void)getGroupList{
    [GroupNetApi getGroupList:^(int code, NSDictionary * _Nullable result) {
        NSLog(@"result:%@",result);
        [self.groupArray addObjectsFromArray:result[@"data"]];
        [self.tableView reloadData];
    } fail:^(NSError * _Nonnull error) {
        
    }];
}

-(void)getFriendlist{
    [FriendNetApi getfriends:nil succ:^(int code, NSDictionary * res) {
        [self.dataArray addObjectsFromArray:res[@"data"]];
        //NSLog(@"self.friendlist:%@",self.friendlist);
        
        [self.tableView reloadData];
        
    } fail:^(NSError * _Nonnull error) {
        
    }];
}

#pragma mark event
- (void)backToChat{
    NSLog(@"backToChat");
    [self dismissViewControllerAnimated:YES completion:nil];
}

#pragma mark private
- (void)sendForwardMessageWithFriend:(NSDictionary *)friend Type:(NSInteger)type{
    NSLog(@"44444");
    NSDate *now = [NSDate date];
    NSTimeInterval trt = [now timeIntervalSince1970];
    NSInteger time = trt*1000;
    NSDictionary * userInfo = [UDManager.shareInstance getDDManager:dkuserinfo];
    NSString * typeString = type == 0 ? @"1" : @"0";
    if (!self.isMultiple) {//逐条转发
        for (NSDictionary * msg in self.msgArray) {
            time= time+100;
            NSString *strtime = [NSString stringWithFormat:@"%ld",(long)time];
            NSDictionary *Smsgd=@{
                @"messageType":msg[@"messageType"],
                @"chatId":friend[@"id"],
                @"fromId":userInfo[@"id"],
                @"fromName":self.userName,
                @"fromAvatar":self.userAvatar,
                @"content":msg[@"content"],
                @"type":typeString,
                @"reSend":[NSNumber numberWithBool:false],
                @"extend": [msg jk_hasKey:@"extend"] == YES ? msg[@"extend"] : @{
                    @"atAll":@"false",
                    @"atUserIds":@[]
                },
                @"localtime":strtime,
                @"timestamp":strtime,
                
            };
            
            NSDictionary *sendInfo = @{
                @"code":@"2",
                @"message":Smsgd,
            };
            
            NSError *error;
            NSData *jsonData = [NSJSONSerialization dataWithJSONObject:sendInfo options:0 error:&error];
            if (!jsonData) {
                NSLog(@"Got an error: %@", error);
            } else {
                NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
                [GWebSocket.shareInstance sendMsg:jsonString];
                
            }
        }
        [MBProgressHUD showWithText:@"操作成功"];
        [self backToChat];
    }else{//合并转发
        NSString *strtime = [NSString stringWithFormat:@"%ld",(long)time];
        NSDictionary *Smsgd=@{
            @"messageType":@"6",
            @"chatId":friend[@"id"],
            @"fromId":userInfo[@"id"],
            @"fromName":self.userName,
            @"fromAvatar":self.userAvatar,
            @"content":@"聊天记录",
            @"type":typeString,
            @"reSend":[NSNumber numberWithBool:false],
            @"extend": @{@"messageList":self.msgArray},
            @"localtime":strtime,
            @"timestamp":strtime,
        };
        
        NSDictionary *sendInfo = @{
            @"code":@"2",
            @"message":Smsgd,
        };
        
        NSError *error;
        NSData *jsonData = [NSJSONSerialization dataWithJSONObject:sendInfo options:0 error:&error];
        if (!jsonData) {
            NSLog(@"Got an error: %@", error);
        } else {
            NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
            [GWebSocket.shareInstance sendMsg:jsonString];
            [MBProgressHUD showWithText:@"操作成功"];
            [self backToChat];
        }
    }
    
}

#pragma mark tableview delegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (section == 0) {
        return self.groupArray.count;
    }
    return self.dataArray.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 20.f;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 0;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    UIView * header = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 20)];
    UILabel * titleLbl = [[UILabel alloc] initWithFrame:CGRectMake(10, 2, 200, 16)];
    titleLbl.text = section == 0 ? @"群聊" : @"好友";
    titleLbl.textColor = UIColor.whiteColor;
    titleLbl.font = SYSFONT(16);
    [header addSubview:titleLbl];
    return header;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    return nil;
}

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

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0) {
        FriendListCell * cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass(FriendListCell.class) forIndexPath:indexPath];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.backgroundColor = [UIColor clearColor];
        [cell fillWithData:self.groupArray[indexPath.row]];
        return cell;
    }
    
    FriendListCell * cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass(FriendListCell.class) forIndexPath:indexPath];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.backgroundColor = [UIColor clearColor];
    [cell fillWithData:self.dataArray[indexPath.row]];
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    NSLog(@"1111");
    if (indexPath.section == 0) {
        NSDictionary * friendDict = self.groupArray[indexPath.row];
        NSLog(@"222");
        if ([friendDict[@"id"] isEqualToString:self.fromChatId]) {
            [self backToChat];
            return;
        }
        [self sendForwardMessageWithFriend:friendDict Type:0];
    }else{
        NSDictionary * friendDict = self.dataArray[indexPath.row];
        NSLog(@"33333:%@",self.fromChatId);
        NSLog(@"friendDict33333:%@",friendDict);
        if ([friendDict[@"id"] isEqualToString:self.fromChatId]) {
            [self backToChat];
            return;
        }
        [self sendForwardMessageWithFriend:friendDict Type:1];
    }
}

#pragma mark lazy
- (UIImageView *)bgImageView{
    if (!_bgImageView) {
        _bgImageView = [[UIImageView alloc] initWithImage:kImageMake(@"loginBG")];
    }
    return _bgImageView;
}

- (UIButton *)leftBtn{
    if (!_leftBtn) {
        _leftBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [_leftBtn setImage:kImageMake(@"fanhui") forState:UIControlStateNormal];
    }
    return _leftBtn;
}

- (UITableView *)tableView{
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
        _tableView.backgroundColor = UIColor.clearColor;
        _tableView.delegate = self;
        _tableView.dataSource = self;
        [_tableView registerClass:FriendListCell.class forCellReuseIdentifier:NSStringFromClass(FriendListCell.class)];
    }
    return _tableView;
}

- (NSMutableArray *)dataArray{
    if (!_dataArray) {
        _dataArray = [NSMutableArray array];
    }
    return _dataArray;
}

- (NSMutableArray *)groupArray{
    if (!_groupArray) {
        _groupArray = [NSMutableArray array];
    }
    return _groupArray;
}

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

@end
