//
//  FriendController.m
//  AIIM
//
//  Created by gan on 2025/4/20.
//

#import <Foundation/Foundation.h>
#import "FriendController.h"
#import "config.h"
#import <SDWebImage/UIImageView+WebCache.h>
#import "ChatController.h"
#import "ChatListStore.h"
#import "UserNetApi.h"
#import "ChatHistoryController.h"
#import "ReportViewController.h"
#import "FriendNetApi.h"

@interface FriendController()<UITableViewDelegate,UITableViewDataSource>
@property (weak, nonatomic) IBOutlet UIImageView *avatar;
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (weak, nonatomic) IBOutlet UIButton *gotochatBt;



@property(nonatomic, strong) NSMutableArray *cellDatas;
@property(nonatomic, strong) NSDictionary * noDisturbDict;

@property(nonatomic, assign) BOOL isfriend;

@end

@implementation FriendController

-(void)viewDidLoad{
    [super viewDidLoad];
    [self.navigationController setNavigationBarHidden:YES animated:NO];
    NSLog(@"FriendController:%@",self.friendMsg);
    if(self.friendMsg){
        _isfriend=YES;
        [self initCelldata];
        [self getNoDiturbSettingData];
    }
    else{
        _gotochatBt.alpha = 0;
        [self getnetFriendMsg];
        [self chetRelation];
    }
    
    [self initsubView];
}

-(void)initsubView{
    [_tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"cellA"];
    [_tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"cellB"];
    [_tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"cellC"];
    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    _tableView.backgroundColor = [UIColor clearColor];
    _tableView.delegate =self;
    _tableView.dataSource = self;
    
    _avatar.layer.cornerRadius = 25.0f;
    
    _gotochatBt.layer.borderWidth = 0.5f;
//    _gotochatBt.layer.borderColor = [UIColor lightGrayColor].CGColor; //globalColor(GCTypeGreen);
    _gotochatBt.layer.cornerRadius = 8.0f; // 可选，设置圆角
    _gotochatBt.backgroundColor=globalColor(GCTypeGreen);
    _gotochatBt.tintColor = [UIColor blackColor];
    
}

-(void)initCelldata{
    NSString *stravatar = self.friendMsg[@"avatar"]?:@"";
    [_avatar sd_setImageWithURL:[NSURL URLWithString:stravatar] placeholderImage:[UIImage imageNamed:@"Avatar"]];
    NSDictionary *d1 =@{
        @"name":@"FriendCtr-mingzi",
        @"image":@"wgerenxx",
        @"detetle":self.friendMsg[@"name"]
    };
    NSDictionary *d2 =@{
        @"name":@"FriendCtr-shuji",
        @"image":@"wgerenxx",
        @"detetle":self.friendMsg[@"mobile"]?:@""
    };
    NSDictionary *d3 =@{
        @"name":@"FriendCtr-youxiang",
        @"image":@"wgerenxx",
        @"detetle":self.friendMsg[@"email"]?:@""
    };
    NSDictionary *d4 =@{
        @"name":@"FriendCtr-liaotanjl",
        @"image":@"wgerenxx",
    };
    NSDictionary *d5 =@{
        @"name":@"FriendCtr-toushujb",
        @"image":@"wgerenxx",
    };
    NSDictionary *d6 =@{
        @"name":@"FriendCtr-jiaruhmd",
        @"image":@"wgerenxx",
    };
    NSDictionary *d7 =@{
        @"name":@"FriendCtr-xiaoximdr",
        @"image":@"wgerenxx",
    };
    _cellDatas = [[NSMutableArray alloc] init];
    [_cellDatas addObject:d1];
    [_cellDatas addObject:d2];
    [_cellDatas addObject:d3];
    [_cellDatas addObject:d4];
    [_cellDatas addObject:d5];
    [_cellDatas addObject:d6];
    [_cellDatas addObject:d7];
    
}

-(void)getnetFriendMsg{
    [UserNetApi getUserinfo_id:self.friendId succ:^(int code, NSDictionary * res) {
        NSLog(@"res:%@",res);
        self.friendMsg = res[@"data"];
        [self getNoDiturbSettingData];
        [self initCelldata];
        [self->_tableView reloadData];
    } fail:^(NSError * _Nonnull error) {
        
    }];
}

-(void)getNoDiturbSettingData{
    [FriendNetApi getNoDisturbSetting:self.friendMsg[@"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.friendMsg[@"id"],
        @"chatId":self.friendMsg[@"id"]
    };
    [FriendNetApi saveNoDisturbSetting:param succ:^(int code, NSDictionary * _Nullable result) {
        [MBProgressHUD showWithText:result[@"msg"]];
    } fail:^(NSError * _Nonnull error) {
        
    }];
}

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

- (IBAction)gotoBack:(id)sender {
    NSLog(@"gotoBack--------");
    [self dismissViewControllerAnimated:YES completion:nil];
}



- (IBAction)gotochatView:(id)sender {
    
    NSDictionary *data=self.self.friendMsg;
    UIStoryboard *board = [UIStoryboard storyboardWithName:@"Main" bundle:[NSBundle mainBundle]];
    
    ChatController *chatctr = [board instantiateViewControllerWithIdentifier:@"ChatController"];
    
    UINavigationController *uiNavC = [[UINavigationController alloc] initWithRootViewController:chatctr];
    
    uiNavC.modalPresentationStyle = UIModalPresentationFullScreen;
    
    chatctr.chatId = data[@"id"];
    chatctr.type = 0;
    ChatListStore.shareInstance.chatId =data[@"id"];
    chatctr.titlename = data[@"name"];
    chatctr.avatar = data[@"avatar"];
    [self presentViewController :uiNavC animated:YES completion:nil];
    
}



- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    NSInteger section =indexPath.section;
    NSString *cellT =@"cellC";
    if(section==0||section==1||section==2){
        cellT =@"cellA";
    }
    if(section==3||section==4||section==5){
        cellT =@"cellB";
    }
    
    UITableViewCell *cell =[tableView dequeueReusableCellWithIdentifier:cellT forIndexPath:indexPath];
    
    if(cell==nil){
        cell=[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellT];
    }
    
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.backgroundColor = [UIColor clearColor];
    NSDictionary *time =_cellDatas[section];
    NSString *title = NSLocalizedString(time[@"name"], @"");
    
    if(section==0||section==1||section==2){
        cell.imageView.image = [UIImage imageNamed:time[@"image"]];
        cell.textLabel.text =title;
        cell.textLabel.textColor = [UIColor whiteColor];
        CGRect ctfrm = cell.contentView.frame;
        NSString *detetle=time[@"detetle"];
        
        if([detetle isKindOfClass:[NSNull class]]||detetle.length==0){
            detetle=NSLocalizedString(@"app-nomsg", @"");
        }
        UILabel *titleLb = [[UILabel alloc] initWithFrame:CGRectMake(ctfrm.size.width/3-10, 0, ctfrm.size.width/3*2, 52)];
        titleLb.text =detetle;
        titleLb.textColor = [UIColor whiteColor];
        titleLb.textAlignment = NSTextAlignmentRight;
        titleLb.font = [UIFont systemFontOfSize:17.0f];
        [cell.contentView addSubview:titleLb];
    }else if(section==3||section==4||section==5){
        cell.imageView.image = [UIImage imageNamed:time[@"image"]];
        cell.textLabel.text =title;
        cell.textLabel.textColor = [UIColor whiteColor];
        UIImageView *right = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"arrow-right"]];
        CGRect ctfrm = cell.contentView.frame;
        right.frame = CGRectMake(ctfrm.size.width-30, 21, 20, 20);
        [cell.contentView addSubview:right];
    }else if (section==6){
        cell.imageView.image = [UIImage imageNamed:time[@"image"]];
        cell.textLabel.text =title;
        cell.textLabel.textColor = [UIColor whiteColor];
        
        CGRect ctfrm = cell.contentView.frame;
        UISwitch *switchButton = [[UISwitch alloc] initWithFrame:CGRectMake(ctfrm.size.width-66, 10, 20, 10)];
        if (self.noDisturbDict && [self.noDisturbDict jk_hasKey:@"id"]) {
            [switchButton setOn:YES];
        }else{
            [switchButton setOn:NO];
        }
        [switchButton addTarget:self action:@selector(switchAction:) forControlEvents:UIControlEventValueChanged];
        [cell.contentView addSubview:switchButton];
    }
    
    cell.contentView.layer.borderWidth = 0.5f;
    cell.contentView.layer.borderColor = [UIColor lightGrayColor].CGColor; //globalColor(GCTypeGreen);
    cell.contentView.layer.cornerRadius = 8.0f; // 可选，设置圆角
    return cell;

}

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

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    NSLog(@"indexPath:%ld",(long)indexPath.section);
    if(indexPath.section==3){
        if(!self.isfriend){
            [MBProgressHUD showWithText:NSLocalizedString(@"login-agreed", @"")];
            return;
        }
        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.friendMsg[@"id"];
        chatctr.type = 0;
        chatctr.titlename = self.friendMsg[@"name"];
        chatctr.avatar = self.friendMsg[@"avatar"];
        [self presentViewController :uiNavC animated:YES completion:nil];
    }
    
    if(indexPath.section==4){
        
        ReportViewController *Reportctr = [[ReportViewController alloc] init];
        UINavigationController *uiNavC = [[UINavigationController alloc] initWithRootViewController:Reportctr];
        uiNavC.modalPresentationStyle = UIModalPresentationFullScreen;
        Reportctr.friendMsg = self.friendMsg;
        Reportctr.friendId = self.friendMsg[@"id"];
        Reportctr.friendName = self.friendMsg[@"name"];
        Reportctr.friendAvatar = self.friendMsg[@"avatar"];
        [self presentViewController :uiNavC animated:YES completion:nil];
    }
    
    
    if (indexPath.section == 5) {
        //拉黑
        NSString *msgnot = [NSString stringWithFormat:@"%@%@",self.friendMsg[@"name"],NSLocalizedString(@"FriendCtr-jiaruhmd", @"")];
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"FriendCtr-jiaruhmd", @"")
                                                                      message:msgnot
                                                               preferredStyle:UIAlertControllerStyleAlert];
         
        UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"Common_cancel",@"取消")
                                                               style:UIAlertActionStyleCancel
                                                             handler:^(UIAlertAction * action) {
            // 点击取消后的操作
        }];
        UIAlertAction *okAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"Common_confirm", @"确定")
                                                         style:UIAlertActionStyleDefault
                                                       handler:^(UIAlertAction * action) {
            [self AddToBlacklist:self.friendMsg[@"id"]];
            // 点击确定后的操作
        }];
        [alert addAction:cancelAction];
        [alert addAction:okAction];
        [self presentViewController:alert animated:YES completion:nil];
        
    }
}

-(void)AddToBlacklist:(NSString *)friendId{
    [FriendNetApi AddToBlacklistWithId:self.friendMsg[@"id"] succ:^(int code, NSDictionary * _Nullable result) {
        [MBProgressHUD showWithText:NSLocalizedString(@"friendCtr-caozuocg", @"")];
    } fail:^(NSError * _Nonnull error) {
        [MBProgressHUD showWithText:NSLocalizedString(@"AppLock_fail", @"")];
    }];
}

-(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==1||section==3||section==4){
//        height =0.0;
//    }
    return height;
}

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


-(void)chetRelation{
    [FriendNetApi isfriend:self.friendId succ:^(int code, NSDictionary * res) {
        NSLog(@"isfriend:%@",[res[@"data"] class]);
        BOOL state = res[@"data"];
        if(state){
            NSLog(@"isfriend1:");
            self.isfriend = true;
        }
        else{
            NSLog(@"isfriend2:");
            self.isfriend=false;
            self->_gotochatBt.alpha = 0;
        }
    } fail:^(NSError * _Nonnull error) {
        
    }];
}


@end
