//
//  ChatIndexController.m
//  AIIM
//
//  Created by gan on 2025/4/6.
//

#import <Foundation/Foundation.h>
#import "ChatIndexController.h"
#import "ChatListCell.h"
#import "ChatListStore.h"
#import "ChatController.h"
#import "ChatNetApi.h"
#import <Bugly/Bugly.h>


@interface ChatIndexController()<UITableViewDelegate,UITableViewDataSource,ChatListStoreDelegate>
@property (weak, nonatomic) IBOutlet UITableView *_tableView;


@end

@implementation ChatIndexController

- (UIStatusBarStyle)preferredStatusBarStyle {
    return UIStatusBarStyleLightContent;
}

-(void)viewDidLoad{
    [super viewDidLoad];
    NSLog(@"ChatIndexController viewDidLoad");
    self._tableView.delegate = self;
    self._tableView.dataSource = self;
    self._tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self._tableView.backgroundColor = [UIColor clearColor];
    UINib *nib = [UINib nibWithNibName:@"ChatListCell" bundle:nil];
    [self._tableView registerNib:nib forCellReuseIdentifier:@"chat"];
    
    //[self._tableView registerClass:[ChatListCell class] forCellReuseIdentifier:@"chat"]; // 使用 Storyboard 时不需要这行代码，除非你混合使用 Storyboard 和代码配置 Cell。
//    ChatListStore.shareInstance.delegate = self;
    //[ChatListStore.shareInstance reloadData:YES];
}

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    NSLog(@"ChatIndexController viewWillAppear");
    [self reloadList];
}

-(void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    NSLog(@"ChatIndexController viewDidAppear");
//    NSDictionary *userinfo = [UDManager.shareInstance getDDManager:dkuserinfo];
//    [Bugly reportException:[NSException exceptionWithName:@"ChatIndexController viewDidAppear" reason:[NSString stringWithFormat:@"数量：%@",userinfo[@"name"]] userInfo:nil]];
    
}

-(void)reloadList{
    ChatListStore.shareInstance.delegate = self;
    ChatListStore.shareInstance.chatId =@"";
    [ChatListStore.shareInstance reloadData:true];
    NSLog(@"ChatIndexController reloadList");
}

-(void)viewDidDisappear:(BOOL)animated{
    [super viewDidDisappear:animated];
    NSLog(@"ChatIndexController viewDidDisappear");
    ChatListStore.shareInstance.delegate = nil;
}

#pragma mark ChatListStoreDelegate
-(void)ChatListChange:(NSArray *)array{
    
    self.chatlist = [NSMutableArray arrayWithArray:array];
    NSLog(@"self.chatlist:%@",self.chatlist);
    
    [self._tableView reloadData];
}

#pragma mark UITableViewDelegate
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.chatlist.count;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    NSDictionary *data=self.chatlist[indexPath.row];
    if(data){
        ChatListCell *cell =[tableView dequeueReusableCellWithIdentifier:@"chat" forIndexPath:indexPath];
        if(cell==nil){
            cell=[[ChatListCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"chat"];
        }
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.backgroundColor = [UIColor clearColor];
        [cell fillWithData:data];
        return cell;
    }
    return nil;
}

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

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    NSDictionary *data=self.chatlist[indexPath.row];
    UIStoryboard *board = [UIStoryboard storyboardWithName:@"Main" bundle:[NSBundle mainBundle]];
    
    ChatController *chatctr = [board instantiateViewControllerWithIdentifier:@"ChatController"];
    
    UINavigationController *uiNavC = [[UINavigationController alloc] initWithRootViewController:chatctr];
    
    uiNavC.modalPresentationStyle = UIModalPresentationFullScreen;
    
    //[self.navigationController pushViewController:chatctr animated:YES];
    NSString *strtype = data[@"type"];
    chatctr.chatId = data[@"id"];
    chatctr.type = strtype.intValue;
    ChatListStore.shareInstance.chatId =data[@"id"];
    chatctr.titlename = data[@"name"];
    chatctr.avatar = data[@"avatar"];
    //chatctr.modalPresentationStyle = UIModalPresentationFullScreen;
    // 打开新页面为模态形式
    //[self presentViewController:chatctr animated:YES completion:nil];
    [self presentViewController :uiNavC animated:YES completion:nil];

}


- (UISwipeActionsConfiguration *)tableView:(UITableView *)tableView trailingSwipeActionsConfigurationForRowAtIndexPath:(NSIndexPath *)indexPath {
    weakSelf(self);
    NSDictionary *data=self.chatlist[indexPath.row];
    BOOL istopMessage = NO;
    if ([data jk_hasKey:@"top"]) {
        istopMessage = [data[@"top"] boolValue];
    }
    NSString * chatId = data[@"id"];
//    // 创建置顶操作
    UIContextualAction * topAction = [UIContextualAction contextualActionWithStyle:UIContextualActionStyleNormal title:istopMessage?@"取消置顶":@"置顶" handler:^(UIContextualAction * _Nonnull action, __kindof UIView * _Nonnull sourceView, void (^ _Nonnull completionHandler)(BOOL)) {
        if (istopMessage) {//取消置顶聊天
            [weakself cancelTopChatWithId:chatId];
            [ChatListStore.shareInstance cancelTopChat:data];
        }else{//置顶聊天
            [weakself topChatWithId:chatId];
            [ChatListStore.shareInstance topChat:data];
        }
        completionHandler(YES);
    }];
    topAction.backgroundColor = UIColor.orangeColor;
    
    // 创建删除操作
    UIContextualAction *deleteAction = [UIContextualAction contextualActionWithStyle:UIContextualActionStyleDestructive
                                                                               title:@"删除"
                                                                             handler:^(UIContextualAction * _Nonnull action, __kindof UIView * _Nonnull sourceView, void (^ _Nonnull completionHandler)(BOOL)) {
        
        // 删除聊天
        [weakself deleteChatWith:chatId];
        
        // 更新数据
        [ChatListStore.shareInstance deleteChat:data];
        [weakself.chatlist removeObject:data];
        [weakself._tableView reloadData];
        
        // 告诉系统操作已完成
        completionHandler(YES);
    }];
    
    // 设置删除按钮颜色
    deleteAction.backgroundColor = [UIColor redColor];
    
    // 创建配置并返回
    UISwipeActionsConfiguration *config = [UISwipeActionsConfiguration configurationWithActions:@[topAction,deleteAction]];
    config.performsFirstActionWithFullSwipe = YES; // 完全滑动直接执行删除
    return config;
}


- (void)deleteChatWith:(NSString *)chatId{
    [ChatNetApi removechat:chatId succ:^(int code, NSDictionary * _Nullable result) {
        if (result[@"msg"]) {
            [MBProgressHUD showWithText:result[@"msg"]];
        }
    } fail:^(NSError * _Nonnull error) {
        
    }];
}


#pragma mark api
- (void)topChatWithId:(NSString *)chatId{

    [ChatNetApi settopchats:chatId succ:^(int code, NSDictionary * _Nullable result) {
        if (result[@"msg"]) {
            [MBProgressHUD showWithText:result[@"msg"]];
            // 更新数据
//            [ChatListStore.shareInstance reloadData:YES];
        }
    } fail:^(NSError * _Nonnull error) {
        
    }];
}

- (void)cancelTopChatWithId:(NSString *)chatId{
    [ChatNetApi canceltopchat:chatId succ:^(int code, NSDictionary * _Nullable result) {
        if (result[@"msg"]) {
            [MBProgressHUD showWithText:result[@"msg"]];
            // 更新数据
//            [ChatListStore.shareInstance reloadData:YES];
        }
    } fail:^(NSError * _Nonnull error) {
        
    }];
}


@end
