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

#import <Foundation/Foundation.h>
#import "FriendListController.h"
#import "FriendListCell.h"
#import "FriendNetApi.h"
#import "config.h"
#import "FriendController.h"
#import "EXFriendController.h"
#import "addFriendController.h"
#import "AppDelegate.h"
@interface FriendListController()<UITableViewDelegate,UITableViewDataSource>


@property (weak, nonatomic) IBOutlet UILabel *titleLb;
@property (weak, nonatomic) IBOutlet UITableView *_tableView;
@property (weak, nonatomic) IBOutlet UIView *topBview;
@property (weak, nonatomic) IBOutlet UILabel *countLb;

@property (nonatomic,strong) UIView *markView;
@property (strong, nonatomic) NSTimer *timer;
@end

@implementation FriendListController

- (UIStatusBarStyle)preferredStatusBarStyle {
    return UIStatusBarStyleLightContent;
}

-(void)viewDidLoad{
    [super viewDidLoad];
    
    _titleLb.text = NSLocalizedString(@"TabBarItem2", @"");
    
    self._tableView.delegate = self;
    self._tableView.dataSource = self;
    self._tableView.backgroundColor = [UIColor clearColor];
    [self._tableView registerClass:[FriendListCell class] forCellReuseIdentifier:@"friend"]; // 使用 Storyboard 时不需要这行代码，除非你混合使用 Storyboard 和代码配置 Cell。
    _topBview.backgroundColor=globalColor(GCTypeDark3);
    _topBview.layer.cornerRadius = 8.0f;
    
    _countLb.backgroundColor = globalColor(GCTypeOrangeR);
    _countLb.textColor = [UIColor whiteColor];
    _countLb.layer.cornerRadius = 15.0f; // 设置圆角
    _countLb.layer.masksToBounds = YES; // 防止子视图超出边界
    _countLb.alpha = 0;
    
    _markView=[[UIView alloc] init];
    [self.view addSubview:_markView];
    
    
    [self initpopView];
}

-(void)viewWillAppear:(BOOL)animated{
    [self getFriendlist];
    [self getexfriends];
    [self startTimer];
}
-(void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [self endTimer];
}


#pragma mark 定时服务
-(void)startTimer{
    if(self.timer==nil){
        self.timer = [NSTimer scheduledTimerWithTimeInterval:10 target:self selector:@selector(TimerAction) userInfo:nil repeats:YES];
        [self.timer setFireDate:[NSDate distantPast]];
        [[NSRunLoop currentRunLoop] addTimer:_timer forMode:NSRunLoopCommonModes];
    }
    
}

-(void)endTimer{
    [self.timer invalidate];
    self.timer = nil;
}

-(void)TimerAction{
    //处理定时触发事件
    [self getexfriends];
}



-(void)getFriendlist{
    [FriendNetApi getfriends:nil succ:^(int code, NSDictionary * res) {
        NSLog(@"self.friendlist:%@",res);
        NSNumber *codeD = res[@"code"];
        if([codeD intValue]==401){
            [[NSNotificationCenter defaultCenter] postNotificationName: nkonLogoutSucc object:nil];
            return;
        }
        self.friendlist = res[@"data"];
        NSLog(@"self.friendlist:%@",self.friendlist);
        if(self.friendlist){
            [self._tableView reloadData];
        }
    } fail:^(NSError * _Nonnull error) {
        
    }];
}

-(void)getexfriends{
    [FriendNetApi getvalidateList:nil succ:^(int code, NSDictionary * res) {
        NSLog(@"getvalidateList res:%@",res);
        NSArray *array = res[@"data"];
        if(array.count>0){
            self.countLb.alpha = 1;
            self.countLb.text = [NSString stringWithFormat:@"%lu",(unsigned long)array.count];
        }
        else{
            self.countLb.alpha = 0;
        }
        
    } fail:^(NSError * _Nonnull error) {
        NSLog(@"error:%@",error);
    }];
}

-(void)initpopView{
    
   
    UITapGestureRecognizer *gotoex = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(gotoexFriend)];
    // 将手势添加到主视图上
    [_topBview addGestureRecognizer:gotoex];
    
    
}


-(void)gotoexFriend{
    UIStoryboard *board = [UIStoryboard storyboardWithName:@"Main" bundle:[NSBundle mainBundle]];
    EXFriendController *friendctr = [board instantiateViewControllerWithIdentifier:@"EXFriendController"];
    UINavigationController *uiNavC = [[UINavigationController alloc] initWithRootViewController:friendctr];
    uiNavC.modalPresentationStyle = UIModalPresentationFullScreen;
    [self presentViewController :uiNavC animated:YES completion:nil];
    
    AppDelegate *app = (AppDelegate *)[UIApplication sharedApplication].delegate;
    [app resetAddFriendBadgeCount];
    
}


- (IBAction)addNewFriend:(id)sender {
    
    UIStoryboard *board = [UIStoryboard storyboardWithName:@"Main" bundle:[NSBundle mainBundle]];
    addFriendController *addfriendctr = [board instantiateViewControllerWithIdentifier:@"addFriendController"];
    UINavigationController *uiNavC = [[UINavigationController alloc] initWithRootViewController:addfriendctr];
    uiNavC.modalPresentationStyle = UIModalPresentationFullScreen;
    [self presentViewController :uiNavC animated:YES completion:nil];
    
//    [self showpopView];
}

#pragma mark UITableViewDelegate

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    NSLog(@"numberOfRowsInSection:%lu",(unsigned long)self.friendlist.count);
    return self.friendlist.count;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    NSDictionary *data=self.friendlist[indexPath.row];
    NSLog(@"cellForRowAtIndexPath:%@",data);
    if(data){
        
        FriendListCell *cell =[tableView dequeueReusableCellWithIdentifier:@"friend" forIndexPath:indexPath];
        if(cell==nil){
            cell=[[FriendListCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"friend"];
        }
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.backgroundColor = [UIColor clearColor];
        [cell fillWithData:data];
        return cell;
    }
    return nil;
}

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

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    NSLog(@"didSelectRowAtIndexPath:%@",indexPath);
    
    NSDictionary *data=self.friendlist[indexPath.row];
    UIStoryboard *board = [UIStoryboard storyboardWithName:@"Main" bundle:[NSBundle mainBundle]];
    FriendController *friendctr = [board instantiateViewControllerWithIdentifier:@"FriendController"];
    UINavigationController *uiNavC = [[UINavigationController alloc] initWithRootViewController:friendctr];
    uiNavC.modalPresentationStyle = UIModalPresentationFullScreen;
    friendctr.friendMsg = data;
    [self presentViewController :uiNavC animated:YES completion:nil];
}

-(UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath {
     return UITableViewCellEditingStyleDelete;
 }
  
 -(void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // 从数据源中移除数据项
        NSLog(@"indexPath:%ld",(long)indexPath.row);
        [self deleteFriend:indexPath.row];
        // 更新表格视图
        //[tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    }
    NSLog(@"1111111");
}
-(void)deleteFriend:(NSInteger)index{
    if(self.friendlist.count>index){
        NSDictionary *dic = self.friendlist[index];
        [FriendNetApi deletefriend:dic[@"id"] succ:^(int code, NSDictionary * res) {
            NSMutableArray *tempArray = [NSMutableArray arrayWithArray:self.friendlist];
            [tempArray removeObjectAtIndex:index];
            self.friendlist = tempArray;
            [self._tableView reloadData];
        } fail:^(NSError * _Nonnull error) {
            ;
        }];
    }
}


@end
