Files
yinmeng-ios/xplan-ios/Main/Message/View/SessionList/SessionListViewController.m
2022-09-08 11:33:42 +08:00

398 lines
13 KiB
Objective-C

//
// SessionListViewController.m
// xplan-ios
//
// Created by zu on 2021/11/25.
//
#import "SessionListViewController.h"
#import "SessionListCell.h"
#import "SessionDiscoverNewTableViewCell.h"
#import "SessionViewController.h"
#import "ThemeColor.h"
#import "XPMacro.h"
#import "ClientConfig.h"
#import "Api+Mine.h"
#import "AccountInfoStorage.h"
///Model
#import "UserInfoModel.h"
///View
#import "XPSessionFindNewViewController.h"
#import "TTPopUp.h"
NSString * const kMessageShowReadDotKey = @"kMessageShowReadDotKey";
#import <Masonry/Masonry.h>
@interface SessionListViewController ()<UITableViewDataSource, UITableViewDelegate, NIMLoginManagerDelegate, NIMConversationManagerDelegate>
@property (nonatomic,strong) UIView *customNavigationBar;
@property (nonatomic,strong) UILabel *titleLabel;
@property (nonatomic, strong) UIButton *allReadButton;
/**
* 会话列表
*/
@property (nonatomic, strong) UITableView *sessionListView;
/**
* 最近会话集合
*/
@property (nonatomic, strong) NSMutableArray<NIMRecentSession *> *recentSessions;
@property (nonatomic, assign) SessionListOpenType openType;
///用户信息
@property (nonatomic,strong) UserInfoModel *userInfo;
@end
@implementation SessionListViewController
- (void)dealloc {
[[NIMSDK sharedSDK].conversationManager removeDelegate:self];
[[NIMSDK sharedSDK].loginManager removeDelegate:self];
}
- (BOOL)isHiddenNavBar {
return YES;
}
- (instancetype)initWithType:(SessionListOpenType)type {
self = [self init];
if (self) {
_openType = type;
}
return self;
}
- (instancetype)init {
self = [super init];
if (self) {
_openType = SessionListOpenTypeDefault;
[self initDatas];
[[NIMSDK sharedSDK].conversationManager addDelegate:self];
[[NIMSDK sharedSDK].loginManager addDelegate:self];
///置顶会话同步
[[NIMSDKConfig sharedConfig] setShouldSyncStickTopSessionInfos:YES];
}
return self;
}
- (void)viewDidLoad {
[super viewDidLoad];
[self getUserInfo];
[self initViews];
[self initLayout];
}
- (void)getUserInfo {
NSString * uid = [AccountInfoStorage instance].getUid;
[Api getUserInfo:^(BaseModel * _Nullable data, NSInteger code, NSString * _Nullable msg) {
if (code == 200) {
UserInfoModel * userInfo = [UserInfoModel modelWithDictionary:data.data];
self.userInfo = userInfo;
[self.sessionListView reloadData];
}
} uid:uid];
}
- (void)initViews {
self.title = @"消息";
if (self.openType == SessionListOpenTypeDefault) {
[self.customNavigationBar addSubview:self.titleLabel];
[self.view addSubview:self.customNavigationBar];
[self.customNavigationBar addSubview:self.allReadButton];
}
[self.view addSubview:self.sessionListView];
}
- (void)initLayout {
if (self.openType == SessionListOpenTypeDefault) {
[self.titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
make.center.mas_equalTo(self.customNavigationBar);
}];
[self.allReadButton mas_makeConstraints:^(MASConstraintMaker *make) {
make.right.mas_equalTo(-16);
make.width.height.mas_equalTo(30);
make.centerY.mas_equalTo(self.customNavigationBar);
}];
}
[self.sessionListView mas_makeConstraints:^(MASConstraintMaker *make) {
make.left.right.bottom.mas_equalTo(self.view);
if (self.openType == SessionListOpenTypeDefault) {
make.top.mas_equalTo(self.customNavigationBar.mas_bottom);
} else {
make.top.mas_equalTo(self.view);
}
}];
}
- (void)initDatas {
[self.recentSessions removeAllObjects];
_recentSessions = [[NIMSDK sharedSDK].conversationManager.allRecentSessions mutableCopy];
__block int unreadCount = 0;
NSMutableArray<NSString *> * uids = [[NSMutableArray alloc] init];
[self.recentSessions enumerateObjectsUsingBlock:^(NIMRecentSession * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
[uids addObject:obj.session.sessionId];
unreadCount += obj.unreadCount;
}];
[self setTabBarItemBadge:unreadCount];
[[NIMSDK sharedSDK].userManager fetchUserInfos:uids completion:nil];
NIMLoadRecentSessionsOptions *options = [[NIMLoadRecentSessionsOptions alloc] init];
options.sortByStickTopInfos = YES;
[NIMSDK.sharedSDK.chatExtendManager loadRecentSessionsWithOptions:options completion:^(NSError * _Nullable error, NSArray<NIMRecentSession *> * _Nullable recentSessions) {
if (error) {
// handle error
return;
}
}];
}
#pragma mark - UITableViewDelegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
if (indexPath.section == 0) {
SessionDiscoverNewTableViewCell * cell = [tableView cellForRowAtIndexPath:indexPath];
cell.hiddenDotView = YES;
[[NSUserDefaults standardUserDefaults] setBool:YES forKey:kMessageShowReadDotKey];
XPSessionFindNewViewController * findNewVC = [[XPSessionFindNewViewController alloc] init];
[self.navigationController pushViewController:findNewVC animated:YES];
return;
}
[tableView deselectRowAtIndexPath:indexPath animated:YES];
NIMRecentSession *recentSession = self.recentSessions[indexPath.row];
SessionViewController *vc = [[SessionViewController alloc] initWithSession:recentSession.session];
vc.openType = self.openType;
[self.navigationController pushViewController:vc animated:YES];
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
return 75.f;
}
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
if (indexPath.section == 0) {
return NO;
}
return YES;
}
- (NSArray<UITableViewRowAction *> *)tableView:(UITableView *)tableView editActionsForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewRowAction * deleteAction = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleDefault title:@"置顶" handler:^(UITableViewRowAction * _Nonnull action, NSIndexPath * _Nonnull indexPath) {
NIMRecentSession * session = [self.recentSessions objectAtIndex:indexPath.row];
[[NIMSDK sharedSDK].conversationManager deleteRecentSession:session];
}];
deleteAction.title = @"删除";
deleteAction.backgroundColor = [UIColor redColor];
return @[deleteAction];
}
#pragma mark - UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 2;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
if (section == 0) {
return [ClientConfig shareConfig].configInfo.findNewbieCharmLevel <= self.userInfo.userLevelVo.experLevelSeq ? 1 : 0;
}
return self.recentSessions.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
if (indexPath.section == 0) {
SessionDiscoverNewTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([SessionDiscoverNewTableViewCell class])];
if (cell == nil) {
cell = [[SessionDiscoverNewTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:NSStringFromClass([SessionDiscoverNewTableViewCell class])];
}
BOOL hidden = [[NSUserDefaults standardUserDefaults] boolForKey:kMessageShowReadDotKey];
cell.hiddenDotView = hidden;
return cell;
}
static NSString * cellId = @"cellId";
SessionListCell * cell = [tableView dequeueReusableCellWithIdentifier:cellId];
if (!cell) {
cell = [[SessionListCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellId];
}
NIMRecentSession *recent = self.recentSessions[indexPath.row];
[cell renderWithSession:recent];
return cell;
}
#pragma mark - NIMConversationManagerDelegate
- (void)didLoadAllRecentSessionCompletion {
[self initDatas];
[self.sessionListView reloadData];
}
- (void)didAddRecentSession:(NIMRecentSession *)recentSession
totalUnreadCount:(NSInteger)totalUnreadCount {
[self.recentSessions addObject:recentSession];
[self.recentSessions sortUsingComparator:^NSComparisonResult(id obj1, id obj2) {
NIMRecentSession *item1 = obj1;
NIMRecentSession *item2 = obj2;
if (item1.lastMessage.timestamp < item2.lastMessage.timestamp) {
return NSOrderedDescending;
}
if (item1.lastMessage.timestamp > item2.lastMessage.timestamp) {
return NSOrderedAscending;
}
return NSOrderedSame;
}];
[self.sessionListView reloadData];
[self setTabBarItemBadge:totalUnreadCount];
}
- (void)didUpdateRecentSession:(NIMRecentSession *)recentSession
totalUnreadCount:(NSInteger)totalUnreadCount {
for (NIMRecentSession *recent in self.recentSessions) {
if ([recentSession.session.sessionId isEqualToString:recent.session.sessionId]) {
[self.recentSessions removeObject:recent];
break;
}
}
NSInteger insert = [self findInsertPlace:recentSession];
[self.recentSessions insertObject:recentSession atIndex:insert];
[self.sessionListView reloadData];
[self setTabBarItemBadge:totalUnreadCount];
}
- (void)didRemoveRecentSession:(NIMRecentSession *)recentSession
totalUnreadCount:(NSInteger)totalUnreadCount {
// 清理本地数据
NSUInteger index = [self.recentSessions indexOfObject:recentSession];
[self.recentSessions removeObjectAtIndex:index];
// 如果删除本地会话后就不允许漫游当前会话,则需要进行一次删除服务器会话的操作
BOOL deleteRemote = NO;
if (deleteRemote) {
[[NIMSDK sharedSDK].conversationManager deleteRemoteSessions:@[recentSession.session]
completion:nil];
}
[self.sessionListView reloadData];
[self setTabBarItemBadge:totalUnreadCount];
}
#pragma mark - NIMLoginManagerDelegate
- (void)onLogin:(NIMLoginStep)step {
if (step == NIMLoginStepSyncOK) {
[self initDatas];
}
}
#pragma mark - JXCategoryListContentViewDelegate
- (UIView *)listView {
return self.view;
}
#pragma mark - Private
- (NSInteger)findInsertPlace:(NIMRecentSession *)recentSession{
__block NSUInteger matchIdx = 0;
__block BOOL find = NO;
[self.recentSessions enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
NIMRecentSession *item = obj;
if (item.lastMessage.timestamp <= recentSession.lastMessage.timestamp) {
*stop = YES;
find = YES;
matchIdx = idx;
}
}];
if (find) {
return matchIdx;
} else {
return self.recentSessions.count;
}
}
- (void)sort{
[self.recentSessions sortUsingComparator:^NSComparisonResult(id obj1, id obj2) {
NIMRecentSession *item1 = obj1;
NIMRecentSession *item2 = obj2;
if (item1.lastMessage.timestamp < item2.lastMessage.timestamp) {
return NSOrderedDescending;
}
if (item1.lastMessage.timestamp > item2.lastMessage.timestamp) {
return NSOrderedAscending;
}
return NSOrderedSame;
}];
}
- (void)setTabBarItemBadge:(NSInteger)value {
if (value > 0) {
[self.tabBarItem setBadgeValue:[NSString stringWithFormat:@"%ld", value]];
} else {
[self.tabBarItem setBadgeValue:nil];
}
}
#pragma mark - action
- (void)allReadButtonClick:(UIButton *)sender {
NSInteger count = [NIMSDK sharedSDK].conversationManager.allUnreadCount;
if (count<1) {
[self showErrorToast:@"暂无未读消息需要清理"];
return;
}
TTAlertConfig * config = [[TTAlertConfig alloc] init];
config.confirmButtonConfig.title = @"清除";
config.message =@"清除当前未读消息提醒?";
[TTPopup alertWithConfig:config confirmHandler:^{
[[NIMSDK sharedSDK].conversationManager markAllMessagesRead];
[self setTabBarItemBadge:0];
[self.sessionListView reloadData];
} cancelHandler:^{
}];
}
- (UIView *)customNavigationBar {
if (!_customNavigationBar) {
CGRect frame = CGRectMake(0, kStatusBarHeight, KScreenWidth, 44);
_customNavigationBar = [[UIView alloc]initWithFrame:frame];
}
return _customNavigationBar;
}
- (UILabel *)titleLabel {
if (!_titleLabel) {
_titleLabel = [[UILabel alloc] initWithFrame:CGRectZero];
_titleLabel.backgroundColor = [UIColor clearColor];
_titleLabel.font = [UIFont systemFontOfSize:18.f weight:UIFontWeightMedium];
_titleLabel.textColor = ThemeColor.mainTextColor;
_titleLabel.text = @"消息";
}
return _titleLabel;
}
- (UITableView *)sessionListView {
if (!_sessionListView) {
_sessionListView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
_sessionListView.separatorStyle = UITableViewCellSeparatorStyleNone;
_sessionListView.backgroundColor = UIColor.clearColor;
_sessionListView.delegate = self;
_sessionListView.dataSource = self;
_sessionListView.showsVerticalScrollIndicator = NO;
}
return _sessionListView;
}
- (NSMutableArray<NIMRecentSession *> *)recentSessions {
if (!_recentSessions) {
_recentSessions = [NSMutableArray array];
}
return _recentSessions;
}
- (UIButton *)allReadButton {
if (!_allReadButton) {
_allReadButton = [[UIButton alloc] init];
[_allReadButton setImage:[UIImage imageNamed:@"sessionList_clear"] forState:UIControlStateNormal];
[_allReadButton addTarget:self action:@selector(allReadButtonClick:) forControlEvents:UIControlEventTouchUpInside];
}
return _allReadButton;
}
@end