//
//  SLAddressBookVc.m
//  SLAiELTS
//
//  Created by Gusont on 2023/4/6.
//

#import "SLAddressBookVc.h"
#import "SLCustNavView.h"
#import "AddressBookCell.h"
#import "UITableView+SCIndexView.h"
#import "SLFriendsModel.h"
#import "SLFriensInfoVc.h"
#import "SLAddFriendVc.h"
#import "SLRecomFriendsVc.h"
#import "SLNearbyPeopleVc.h"

@interface SLAddressBookVc ()<UITableViewDelegate, UITableViewDataSource>
@property (weak, nonatomic) IBOutlet SLCustNavView *navView;
@property (weak, nonatomic) IBOutlet UIButton *tjBtn;
@property (weak, nonatomic) IBOutlet UIButton *fjBtn;
@property (weak, nonatomic) IBOutlet UITableView *tableView;

@property(nonatomic,strong) NSMutableArray *lettersArray;

@property(nonatomic,strong) NSMutableDictionary *nameDic;

@property (nonatomic, strong) UIScrollView *fScrollview;
@end

@implementation SLAddressBookVc

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    NSString *userId = [SLGlobalInfo SharedInstance].loginInfo.user.userId;
    if (userId) {
        NSString *urlStr = self.isSelFriend ? @"/api/Friend/ReminderToSee" : @"/api/Chat/GetContactsList";
        [[SLHttpCenter SharedInstance] getWithUrl:urlStr parameter:@{} success:^(id responseObject) {
            NSArray *datas = [responseObject objectForKey:@"data"];
            NSArray *friendsModel = [SLFriendsModel mj_objectArrayWithKeyValuesArray:datas];
            [friendsModel enumerateObjectsUsingBlock:^(SLFriendsModel *obj, NSUInteger idx, BOOL * _Nonnull stop) {
                obj.userId = [obj valueForKey:@"contactsId"];
                obj.isEdit = self.isSelFriend;
                [self.selFriendsArr enumerateObjectsUsingBlock:^(SLFriendsModel * _Nonnull obj1, NSUInteger idx, BOOL * _Nonnull stop1) {
                    if ([obj.userId isEqualToString:obj1.userId]) {
                        obj.isSelected = YES;
                        *stop1 = YES;
                    }
                }];
            }];
            [self handleLettersArray:friendsModel];
            self.tableView.sc_indexViewDataSource = self.lettersArray;
            [self.tableView reloadData];
        } failure:^(SPRequestError *error) {
            
        }];
    }
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    if (@available(iOS 15.0, *)) {
        self.tableView.sectionHeaderTopPadding = 0;
    } else {
        // Fallback on earlier versions
    }
    [self.tableView registerNibCellWithReuseIdentifierClass:AddressBookCell.class];
    self.lettersArray = [[NSMutableArray alloc] init];
    self.nameDic = [[NSMutableDictionary alloc] init];
    if (self.isSelFriend) {
        self.navigationBar.hidden = NO;
        YMBarButtonItem *rightBarItem = [[YMBarButtonItem alloc] initWithTitle:@"保存  " target:self action:@selector(preserveBtnClick)];
        rightBarItem.titleInsets = UIEdgeInsetsMake(0, 0, 0, 20);
        self.navigationBar.rightBarButtonItem = rightBarItem;
        [self.tableView mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.left.right.equalTo(self.view);
            make.top.mas_equalTo(kNavBarHeight);
            make.bottom.mas_equalTo(-kSafeAreaBottom - 80);
        }];
        
        UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(16, kSCREEN_HEIGHT - kSafeAreaBottom - 74 , kSCREEN_WIDTH, 24)];
        label.text = @"选择好友（0）";
        label.font = [UIFont boldSystemFontOfSize:16];
        label.tag = 55555;
        label.textColor = [UIColor blackColor];
        [self.view addSubview:label];
        
        UIScrollView *scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, kSCREEN_HEIGHT - kSafeAreaBottom - 45 , kSCREEN_WIDTH, 80)];
        scrollView.showsVerticalScrollIndicator = NO;
        scrollView.showsHorizontalScrollIndicator = NO;
        [self.view addSubview:scrollView];
        self.fScrollview = scrollView;
        [self refreshSelFriendsWith:self.selFriendsArr];
    }else {
        self.navigationBar.hidden = YES;
        NSArray *navs = @[[SLPageModelDetail initWithTitle:@"新增好友" bgImage:@"icon_home_add"],
                          [SLPageModelDetail initWithTitle:@"搜索" bgImage:@"icon_home_search"]];
        [self.navView confignNavViewWith:navs];
        WS(weakSelf);
        self.navView.rightBtnBlock = ^(YMNavBarRightBtnIdx idx) {
            
        };
        [self.navView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.height.mas_equalTo(kNavBarHeight);
        }];
        self.navView.infoLabel.text = @"联系";
        [self.tjBtn layoutButtonWithEdgeInsetsStyle:MKButtonEdgeInsetsStyleTop imageTitleSpace:6];
        [self.fjBtn layoutButtonWithEdgeInsetsStyle:MKButtonEdgeInsetsStyleTop imageTitleSpace:6];
    }
    
    // 配置索引模块
    SCIndexViewConfiguration *configuration = [SCIndexViewConfiguration configuration];
    // 设置item 距离 右侧屏幕的间距
    configuration.indexItemRightMargin = 8.0;
    // 设置item 文字颜色
    configuration.indexItemTextColor = SLColor(@"#555555");
    // 设置item 选中时的背景色
    configuration.indexItemSelectedBackgroundColor = SLBlueColor;
    /// 设置索引之间的间距
    configuration.indexItemsSpace = 4.0;
    
    self.tableView.sc_indexViewConfiguration = configuration;
    self.tableView.sc_translucentForTableViewInNavigationBar = YES;
    self.tableView.sc_startSection = 1;
    self.tableView.backgroundColor = [UIColor clearColor];
    //可以直接添加如下代码即可
    self.tableView.tableFooterView = [[UIView alloc]initWithFrame:CGRectZero];
}

- (IBAction)recomFriendBtnClick:(id)sender {
    SLRecomFriendsVc *vc = (SLRecomFriendsVc *)[SLRecomFriendsVc loadViewControllewWithNib];
    [self navPushViewController:vc animated:YES];
}

- (IBAction)nearbyPeopleBtnClick:(id)sender {
    SLNearbyPeopleVc *vc = (SLNearbyPeopleVc *)[SLNearbyPeopleVc loadViewControllewWithNib];
    [self navPushViewController:vc animated:YES];
}

- (void)preserveBtnClick {
    __block NSMutableArray *marr = [NSMutableArray array];
    [self.nameDic.allValues enumerateObjectsUsingBlock:^(NSArray * obj, NSUInteger idx, BOOL * _Nonnull stop) {
        if ([obj isKindOfClass:NSArray.class]) {
            [obj enumerateObjectsUsingBlock:^(SLFriendsModel * obj1, NSUInteger idx, BOOL * _Nonnull stop) {
                if (obj1.isSelected) {
                    [marr addObject:obj1];
                }
            }];
        }
    }];
    if (self.selFriendsBlock) {
        self.selFriendsBlock(marr);
        [self.navigationController popViewControllerAnimated:YES];
    }
}

- (void)refreshSelFriendsWith:(NSArray *)marr {
    self.fScrollview.contentSize = CGSizeMake(marr.count * 48, 60);
    UILabel *label = [self.view viewWithTag:55555];
    label.text = [NSString stringWithFormat:@"选择好友（%ld）",marr.count];
    [self.fScrollview.subviews enumerateObjectsUsingBlock:^(__kindof UIView * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        [obj removeFromSuperview];
        obj = nil;
    }];
    [marr enumerateObjectsUsingBlock:^(SLFriendsModel *obj, NSUInteger idx, BOOL * _Nonnull stop) {
        UIImageView *imageView = [[UIImageView alloc] init];
        NSString *userImg = [obj getUserHeadUrl];
        [imageView sd_setImageWithURL:[NSURL URLWithString:userImg] placeholderImage:[UIImage imageNamed:@"icon_ellipse"] completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
            
        }];
        imageView.contentMode = UIViewContentModeScaleAspectFill;
        imageView.layer.cornerRadius = 24;
        imageView.clipsToBounds = YES;
        imageView.frame = CGRectMake(40 * idx + 16, 0, 48, 48);
        [self.fScrollview addSubview:imageView];
    }];
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return self.lettersArray.count;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    NSArray *nameArray = [self.nameDic objectForKey:self.lettersArray[section]];
    return nameArray.count;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    AddressBookCell *cell = (AddressBookCell *)[tableView dequeueReusableCellWithIdentifier:@"AddressBookCell"];
    SLFriendsModel *frends = [[self.nameDic objectForKey:self.lettersArray[indexPath.section]] objectAtIndex:indexPath.row];
    cell.frendModel = frends;
    WS(weakSelf);
    cell.selBlock = ^{
        __block NSMutableArray *marr = [NSMutableArray array];
        [weakSelf.nameDic.allValues enumerateObjectsUsingBlock:^(NSArray * obj, NSUInteger idx, BOOL * _Nonnull stop) {
            if ([obj isKindOfClass:NSArray.class]) {
                [obj enumerateObjectsUsingBlock:^(SLFriendsModel * obj1, NSUInteger idx, BOOL * _Nonnull stop) {
                    if (obj1.isSelected) {
                        [marr addObject:obj1];
                    }
                }];
            }
        }];
        [weakSelf refreshSelFriendsWith:marr];
    };
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if (self.isSelFriend) {
        return;
    }
    SLFriendsModel *frends = [[self.nameDic objectForKey:self.lettersArray[indexPath.section]] objectAtIndex:indexPath.row];
    SLFriensInfoVc *vc = [SLFriensInfoVc loadViewControllewWithNib];
    vc.friendModel = frends;
    [self navPushViewController:vc animated:YES];
}

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

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    return [[UIView alloc] initWithFrame:CGRectZero];
}

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

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    UIView *headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, tableView.frame.size.width, 35)];
    headerView.backgroundColor = SLBgColor;
    headerView.tag =10009 + section;
    NSString *letterString =  self.lettersArray[section];
    UILabel *letterLabel = [[UILabel alloc] initWithFrame:CGRectMake(15, headerView.frame.origin.y, headerView.frame.size.width-10, headerView.frame.size.height)];
    letterLabel.text = letterString;
    letterLabel.tag = 222333;
    letterLabel.textColor = SL333Color;
    letterLabel.font = [UIFont systemFontOfSize:14.f];
    [headerView addSubview:letterLabel];
    return headerView;
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 35.01;
}

//处理letterArray，包括按英文字母顺序排序
- (void)handleLettersArray:(NSArray *)dataSource{
    NSMutableDictionary *tempDic = [[NSMutableDictionary  alloc]init];
    for(SLFriendsModel *friends  in dataSource){
        HanyuPinyinOutputFormat *formatter =  [[HanyuPinyinOutputFormat alloc] init];
        formatter.caseType = CaseTypeLowercase;
        formatter.vCharType = VCharTypeWithV;
        formatter.toneType = ToneTypeWithoutTone;
        NSString *outputPinyin=[PinyinHelper toHanyuPinyinStringWithNSString:friends.userName withHanyuPinyinOutputFormat:formatter withNSString:@""];
//        NSLog(@"%@",[[outputPinyin substringToIndex:1] uppercaseString]);
        [tempDic setObject:friends forKey:[[outputPinyin substringToIndex:1] uppercaseString]];
    }
    
    self.lettersArray = tempDic.allKeys.mutableCopy;
    for (NSString *letter in self.lettersArray) {
        NSMutableArray *tempArry = [[NSMutableArray alloc] init];
        for (NSInteger i = 0; i<dataSource.count; i++) {
            SLFriendsModel *friends = dataSource[i];
            HanyuPinyinOutputFormat *formatter =  [[HanyuPinyinOutputFormat alloc] init];
            formatter.caseType = CaseTypeUppercase;
            formatter.vCharType = VCharTypeWithV;
            formatter.toneType = ToneTypeWithoutTone;
            //把friend的userName汉子转为汉语拼音，比如：张磊---->zhanglei
            NSString *outputPinyin=[PinyinHelper toHanyuPinyinStringWithNSString:friends.userName withHanyuPinyinOutputFormat:formatter withNSString:@""];
            if ([letter isEqualToString:[[outputPinyin substringToIndex:1] uppercaseString]]) {
                [tempArry addObject:friends];
            }
        }
        [self.nameDic setObject:tempArry forKey:letter];
    }
    //排序，排序的根据是字母
    NSComparator cmptr = ^(id obj1, id obj2){
        if ([obj1 characterAtIndex:0] > [obj2 characterAtIndex:0]) {
            return (NSComparisonResult)NSOrderedDescending;
        }
        
        if ([obj1 characterAtIndex:0] < [obj2 characterAtIndex:0]) {
            return (NSComparisonResult)NSOrderedAscending;
        }
        return (NSComparisonResult)NSOrderedSame;
    };
    [self.nameDic setObject:UITableViewIndexSearch forKey:@""];
    self.lettersArray = [[NSMutableArray alloc]initWithArray:[self.lettersArray sortedArrayUsingComparator:cmptr]];
    
}

@end
