Files
yinmeng-ios/xplan-ios/Main/Message/View/Session/SessionViewController.m
2023-12-12 11:53:14 +08:00

982 lines
39 KiB
Objective-C

//
// SessionViewController.m
// xplan-ios
//
// Created by zu on 2021/11/28.
//
#import "SessionViewController.h"
#import <Masonry/Masonry.h>
#import <IQKeyboardManager/IQKeyboardManager.h>
#import <TZImagePickerController/TZImagePickerController.h>
#import <MJRefresh/MJRefresh.h>
///Tool
#import "XCCurrentVCStackManager.h"
#import "NIMMessageMaker.h"
#import "XPMacro.h"
#import "UITableView+NIMScrollToBottom.h"
#import "ThemeColor.h"
#import "NSArray+Safe.h"
#import "ClientConfig.h"
#import "Api.h"
#import "Api+Mine.h"
///Model
#import "RoomInfoModel.h"
#import "UserInfoModel.h"
#import "MessageMenuModel.h"
#import "SessionRiskCache.h"
#import "UserGameInfoVo.h"
#import "AttachmentModel.h"
#import "WalletInfoModel.h"
///View
#import "XPSessionMessageHeadView.h"
#import "XPMineUserInfoViewController.h"
#import "XPRoomViewController.h"
#import "RoomHostDelegate.h"
#import "SessionToolbarView.h"
#import "MessageCell.h"
#import "SessionChatLimitView.h"
#import "XPSendGiftView.h"
#import "SessionNavView.h"
#import "SessionInfoViewController.h"
#import "SessionRiskView.h"
#import "XPMineGameOrderDetailsView.h"
///P
#import "MessagePresenter.h"
#import "MessageProtocol.h"
#import "XPSessionMessageGameCell.h"
#import "XPSessionMessageGamePageControl.h"
#import "XPMinePlaceOrderView.h"
#import "XPSessionMessageGameInfoView.h"
#import "XPMineNewRechargeViewController.h"
@interface SessionViewController ()<MessageProtocol, UITableViewDelegate, UITableViewDataSource, NIMChatManagerDelegate, NIMConversationManagerDelegate, NIMMediaManagerDelegate, MessageCellDelegate, SessionToolbarViewDelegate, TZImagePickerControllerDelegate, SessionNavViewDelegate, SessionRiskViewDelegate,XPSessionMessageGameCellDelegate,XPMinePlaceOrderViewDelegate,XPMineGameOrderDetailsViewDelegate,UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout,XPSessionMessageGameInfoViewDelegate>
@property (nonatomic, strong) NIMSession * session;
@property (nonatomic, strong) NSMutableArray<NIMMessage *> * messages;
///导航栏
@property (nonatomic,strong) SessionNavView *sessionNavView;
@property (nonatomic, strong) UITableView * sessionTableView;
///跟随进房卡片
@property (nonatomic, assign) BOOL isShowfollowInRoomView;
@property (nonatomic, strong) UserInfoModel *userInfo;
///输入框
@property (nonatomic,strong) SessionToolbarView *toolbarView;
///最后的一条消息
@property (nonatomic,strong) NIMMessage *lastMessage;
///私聊风险提示
@property (nonatomic,strong) SessionRiskView *riskAlertView;
///占位图
@property(nonatomic,strong) UIView *emptyVeiw;
///游戏点单轮播
@property(nonatomic,strong) UICollectionView *collectionView;
@property(nonatomic,strong) XPSessionMessageGamePageControl *pageControl;
@property (nonatomic, strong) UIStackView *stackView;
///余额
@property(nonatomic, copy)NSString *diamonds;
@property(nonatomic,strong) NSMutableArray *gameArray;
@end
@implementation SessionViewController
- (BOOL)isHiddenNavBar {
return YES;
}
- (void)dealloc {
[[NIMSDK sharedSDK].chatManager removeDelegate:self];
[[NIMSDK sharedSDK].conversationManager removeDelegate:self];
[[NIMSDK sharedSDK].mediaManager removeDelegate:self];
[[NSNotificationCenter defaultCenter] removeObserver:self];
}
- (MessagePresenter *)createPresenter {
return [[MessagePresenter alloc] init];
}
- (instancetype)initWithSession:(NIMSession *)session {
self = [super init];
if (self) {
_session = session;
}
return self;
}
- (void)viewDidLoad {
[super viewDidLoad];
[self initViews];
[self initLayout];
[IQKeyboardManager sharedManager].enable = NO;
[IQKeyboardManager sharedManager].enableAutoToolbar = NO;
[self initHeaderAndFooterRrfresh];
[[NIMSDK sharedSDK].chatManager addDelegate:self];
[[NIMSDK sharedSDK].conversationManager addDelegate:self];
[[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(getAttentionUserNotification) name:@"kAttentionUserNotification" object:nil];
}
-(void)getAttentionUserNotification{
[self.presenter getChatLimitReceiverUid:self.session.sessionId];
dispatch_time_t delayTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC));
dispatch_after(delayTime, dispatch_get_main_queue(), ^{
if ([self showChatRiskView:self.userInfo]==YES) {
self.riskAlertView.warning = self.userInfo.banAccount ? @" 温馨提醒:当前对方账号存在异常,请谨慎来往!" : @"温馨提示:对方和您非好友关系,请注意隐私安全!";
self.riskAlertView.hidden = NO;
self.emptyVeiw.hidden = YES;
}else{
self.riskAlertView.hidden = YES;
self.emptyVeiw.hidden = NO;
}
});
}
- (void)viewWillAppear:(BOOL)animated {
[super viewWillAppear:animated];
[self.presenter getFansLike:self.session.sessionId];
self.sessionNavView.userId = self.session.sessionId;
}
- (void)initHeaderAndFooterRrfresh {
MJRefreshNormalHeader *header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(headerRefresh)];
header.stateLabel.font = [UIFont systemFontOfSize:10.0];
header.lastUpdatedTimeLabel.font = [UIFont systemFontOfSize:10.0];
header.stateLabel.textColor = [ThemeColor secondTextColor];
header.lastUpdatedTimeLabel.textColor = [ThemeColor secondTextColor];
self.sessionTableView.mj_header = header;
[self headerRefresh];
[self initData];
}
- (void)headerRefresh {
if (self.messages.count > 0) {
[[[NIMSDK sharedSDK] conversationManager] messagesInSession:self.session message:self.messages.firstObject limit:20 completion:^(NSError * _Nullable error, NSArray<NIMMessage *> * _Nullable messages) {
[self.sessionTableView.mj_header endRefreshing];
if (error == nil && messages.count > 0) {
for (int i = ((int)messages.count -1); i > 0; i--) {
NIMMessage * message = [messages safeObjectAtIndex1:i];
[self.messages insertObject:message atIndex:0];
}
}
[self.sessionTableView reloadData];
}];
} else {
[[[NIMSDK sharedSDK] conversationManager] messagesInSession:self.session message:nil limit:20 completion:^(NSError * _Nullable error, NSArray<NIMMessage *> * _Nullable messages) {
[self.sessionTableView.mj_header endRefreshing];
if (error == nil) {
[self.messages addObjectsFromArray:messages];
}
[self.sessionTableView reloadData];
[self.sessionTableView nim_scrollToBottom:NO];
}];
}
}
- (UINavigationController *)getKeyWindowNav {
if ([XCCurrentVCStackManager shareManager].getCurrentVC) {
return [XCCurrentVCStackManager shareManager].getCurrentVC.navigationController;
}
return self.navigationController;
}
#pragma mark - Private Method
- (void)initViews {
self.sessionNavView.isInRoom = self.openType == SessionListOpenTypeRoom;
[self.view addSubview:self.sessionNavView];
[self.view addSubview:self.stackView];
[self.stackView addArrangedSubview:self.emptyVeiw];
[self.stackView addArrangedSubview:self.riskAlertView];
[self.view addSubview:self.sessionTableView];
[self.view addSubview:self.toolbarView];
if (self.openType != SessionListOpenTypeRoom) {
[self.stackView addArrangedSubview:self.collectionView];
[self.stackView addArrangedSubview:self.pageControl];
}
}
- (void)initLayout {
[self.sessionNavView mas_makeConstraints:^(MASConstraintMaker *make) {
make.height.mas_equalTo(self.openType == SessionListOpenTypeRoom ? 44 : kNavigationHeight);
make.left.top.right.mas_equalTo(self.view);
}];
[self.stackView mas_makeConstraints:^(MASConstraintMaker *make) {
make.left.right.equalTo(self.view);
make.top.equalTo(self.self.sessionNavView.mas_bottom);
}];
[self.emptyVeiw mas_makeConstraints:^(MASConstraintMaker *make) {
make.left.right.mas_equalTo(self.view);
make.height.mas_equalTo(0);
}];
[self.riskAlertView mas_makeConstraints:^(MASConstraintMaker *make) {
make.left.right.mas_equalTo(self.view);
make.height.mas_equalTo(20);
}];
[self.sessionTableView mas_makeConstraints:^(MASConstraintMaker *make) {
make.left.right.mas_equalTo(self.view);
make.top.mas_equalTo(self.stackView.mas_bottom).mas_offset(10);
make.bottom.mas_equalTo(self.toolbarView.mas_top);
}];
[self.toolbarView mas_makeConstraints:^(MASConstraintMaker *make) {
make.left.right.mas_equalTo(self.view);
make.bottom.mas_equalTo(self.view);
}];
if (self.openType != SessionListOpenTypeRoom) {
[self.collectionView mas_makeConstraints:^(MASConstraintMaker *make) {
make.left.right.mas_equalTo(self.view);
make.height.mas_equalTo(kGetScaleWidth(76));
}];
[self.pageControl mas_makeConstraints:^(MASConstraintMaker *make) {
make.left.right.mas_equalTo(self.view);
make.height.mas_equalTo(kGetScaleWidth(4));
}];
}
}
- (void)viewDidLayoutSubviews{
if (self.openType == SessionListOpenTypeRoom) {
self.view.frame = CGRectMake(0, 0, KScreenWidth, kHalfScreenHeight);
}
}
- (void)initData {
NIMUser * user = [[NIMSDK sharedSDK].userManager userInfo:self.session.sessionId];
if (user) {
self.sessionNavView.title = user.userInfo.nickName;
} else {
self.sessionNavView.title = @"加载中……";
}
[[NIMSDK sharedSDK].conversationManager markAllMessagesReadInSession:self.session];
[self.presenter getChatLimitReceiverUid:self.session.sessionId];
[self.presenter getUserInfo:self.session.sessionId];
self.sessionNavView.userId = self.session.sessionId;
[self getUserWallet];
}
-(void)getUserWallet{
[Api getUserWalletInfo:^(BaseModel * _Nullable data, NSInteger code, NSString * _Nullable msg) {
if(code == 200){
WalletInfoModel * model = [WalletInfoModel modelWithDictionary:data.data];
self.diamonds = model.diamonds;
}
} uid:[AccountInfoStorage instance].getUid ticket:[AccountInfoStorage instance].getTicket];
}
- (BOOL)isExistMessages:(NIMMessage *)message{
BOOL isExist = NO;
NIMMessage * model;
for (NIMMessage *item in self.messages.reverseObjectEnumerator.allObjects) {
if ([item isKindOfClass:[NIMMessage class]] && [item.messageId isEqual:message.messageId]) {
model = item;
isExist = YES;
break;
}
}
if (model) {
model = message;
}
return isExist;
}
- (BOOL)showChatRiskView:(UserInfoModel *)userInfo {
if (userInfo.banAccount) {
return YES;
}
NSString * cacheUid = [[SessionRiskCache shareCache] getCloseChatRiskAlert:self.session.sessionId];
if (cacheUid && [cacheUid isEqualToString:self.session.sessionId]) {
return NO;
}
if ([[NIMSDK sharedSDK].userManager isMyFriend:self.session.sessionId] && !userInfo.banAccount) {
return NO;
}
if ([[ClientConfig shareConfig].configInfo.officialMsgUids containsObject:self.session.sessionId] || [[ClientConfig shareConfig].configInfo.officialAccountUids containsObject:self.session.sessionId]) {
return NO;
}
return YES;
}
#pragma mark - MessageProtocol
-(void)getGamePartnerInfoList:(NSArray *)list{
NSMutableArray *gameTextArray = [NSMutableArray array];
for (UserGameInfoVo *gameInfo in list) {
[gameTextArray addObject:gameInfo.gameName];
NSMutableArray *tagList = [NSMutableArray array];
for (UserGameTagInfo *tagInfo in gameInfo.tags) {
if([tagInfo.tagName isEqualToString:@"段位"]){
gameInfo.tier = tagInfo.tagVal;
}else{
[tagList addObject:tagInfo];
}
}
gameInfo.tags = tagList;
}
self.gameArray = [NSMutableArray arrayWithArray:list];
if(self.isShowfollowInRoomView == YES && list.count == 0){
UserGameInfoVo *gameModel = [UserGameInfoVo new];
gameModel.gameName = @"跟随房间";
[self.gameArray addObject:gameModel];
[gameTextArray addObject:gameModel.gameName];
self.collectionView.hidden = NO;
[self.collectionView reloadData];
[self.sessionTableView nim_scrollToBottom:YES];
return;
}
if(gameTextArray.count > 0){
self.collectionView.hidden = NO;
self.pageControl.hidden = NO;
self.pageControl.pageList = gameTextArray;
self.pageControl.curPage = 0;
[self.collectionView reloadData];
[self.sessionTableView nim_scrollToBottom:YES];
}
}
- (void)onGetLimitChat:(ChatLimitModel *)chatLimit {
BOOL chatDisabled ;
if(chatLimit.model == 2){
chatDisabled = !chatLimit.chat;
}else{
chatDisabled = !chatLimit.chat && self.messages.count <= 0;
}
if (chatDisabled) {
SessionChatLimitView *chatLimitView = [[SessionChatLimitView alloc] initWithChatLimit:chatLimit];
self.sessionTableView.tableHeaderView = chatLimitView;
} else {
self.sessionTableView.tableHeaderView = nil;
}
self.toolbarView.model = chatLimit.model;
self.toolbarView.sendDisabled = chatDisabled;
}
///获取用户信息成功
- (void)onGetSessionUserInfoSuccess:(UserInfoModel *)userInfo {
_userInfo = userInfo;
[self.presenter getGamePartnerInfoListWithUid:@(_userInfo.uid).stringValue];
if (userInfo.nick.length > 0) {
self.sessionNavView.title = userInfo.nick;
}
if (userInfo.roomUid && self.openType != SessionListOpenTypeRoom) {
self.isShowfollowInRoomView = YES;
self.sessionNavView.isShowLive = YES;
if ([self showChatRiskView:userInfo]==YES) {
self.riskAlertView.warning = userInfo.banAccount ? @" 温馨提醒:当前对方账号存在异常,请谨慎来往!" : @" 温馨提示:对方和您非好友关系,请注意隐私安全!";
self.riskAlertView.hidden = NO;
}else{
self.riskAlertView.hidden = YES;
self.emptyVeiw.hidden = NO;
}
} else {
if ([self showChatRiskView:userInfo]) {
self.riskAlertView.warning = userInfo.banAccount ? @" 温馨提醒:当前对方账号存在异常,请谨慎来往!" : @" 温馨提示:对方和您非好友关系,请注意隐私安全!";
self.riskAlertView.hidden = NO;
}else{
self.riskAlertView.hidden = YES;
self.emptyVeiw.hidden = NO;
}
}
}
///获取用户信息失败
- (void)onGetSessionUserInfoFail{
[self.presenter getGamePartnerInfoListWithUid:self.session.sessionId];
}
- (void)getFansLikeSuccess:(BOOL)isLike {
if ([[ClientConfig shareConfig].configInfo.officialMsgUids containsObject:self.session.sessionId] || [[ClientConfig shareConfig].configInfo.officialAccountUids containsObject:self.session.sessionId]) {
self.sessionNavView.isLike = YES;
} else {
self.sessionNavView.isLike = isLike;
}
}
- (void)attentionUserSuccess:(NSString *)uid {
if ([uid isEqualToString:self.session.sessionId]) {
self.sessionNavView.isLike = YES;
}
}
#pragma mark - MessageCellDelegate
- (void)updateMessageSuccess:(NIMMessage *)message {
if ([message.session.sessionId isEqualToString:self.session.sessionId]) {
[self.sessionTableView reloadData];
}
}
- (void)checkGameListInfo:(NIMMessage *)message{
NIMCustomObject *obj = (NIMCustomObject *)message.messageObject;
AttachmentModel * attachment = obj.attachment;
if(attachment.first == CustomMessageType_Initiat_Invitation && attachment.second == Custom_Message_Sub_Initiat_Invitation_Initiating_User){
UserGameInfoVo *gameInfo = [UserGameInfoVo modelWithDictionary:attachment.data];
int type = [gameInfo.toUid isEqualToString:[AccountInfoStorage instance].getUid] ? 1 : 0;
XPMineGameOrderDetailsView *orderView = [[XPMineGameOrderDetailsView alloc]initWithFrame:CGRectMake(0, 0, KScreenWidth, KScreenHeight) type:type];
orderView.gameInfo = gameInfo;
if(type == 0 && self.gameArray.count == 0){
orderView.isHiddenBtn = YES;
}
orderView.isFormChat = YES;
orderView.delegate = self;
[self.view addSubview:orderView];
}
}
- (void)didTapAvatar:(NSString *)uid {
//过滤官方账号
if ([[ClientConfig shareConfig].configInfo.officialMsgUids containsObject:self.session.sessionId] || [[ClientConfig shareConfig].configInfo.officialAccountUids containsObject:self.session.sessionId]) {
return;
}
if (uid.length > 0) {
XPMineUserInfoViewController * infoVC = [[XPMineUserInfoViewController alloc] init];
infoVC.uid = uid.integerValue;
[[self getKeyWindowNav] pushViewController:infoVC animated:YES];
}
}
#pragma mark - UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
return self.gameArray.count;
}
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
return CGSizeMake(KScreenWidth, kGetScaleWidth(76));;
}
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout referenceSizeForFooterInSection:(NSInteger)section{
UserGameInfoVo *gameInfo = [self.gameArray safeObjectAtIndex1:0];
if([gameInfo.gameName isEqualToString:@"跟随房间"]){
return CGSizeMake(0, 0);
}
return CGSizeMake(kGetScaleWidth(102), kGetScaleWidth(76));
}
-(UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
{
UICollectionReusableView *reusableView = nil;
UserGameInfoVo *gameInfo = [self.gameArray safeObjectAtIndex1:indexPath.row];
if([gameInfo.gameName isEqualToString:@"跟随房间"]){
return reusableView;
}
if (kind ==UICollectionElementKindSectionFooter){
XPSessionMessageGameInfoView *footerV = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:NSStringFromClass([XPSessionMessageGameInfoView class]) forIndexPath:indexPath];
footerV.headUrl = self.userInfo.avatar;
footerV.delegate = self;
reusableView = footerV;
}
return reusableView;
}
-(__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
XPSessionMessageGameCell *myCell = [collectionView dequeueReusableCellWithReuseIdentifier:NSStringFromClass([XPSessionMessageGameCell class]) forIndexPath:indexPath];
UserGameInfoVo *gameInfo = [self.gameArray safeObjectAtIndex1:indexPath.row];
if([gameInfo.gameName isEqualToString:@"跟随房间"]){
myCell.userInfo = self.userInfo;
}else{
myCell.gameInfo = gameInfo;
}
myCell.delegate = self;
return myCell;
}
-(void)scrollViewDidScroll:(UIScrollView *)scrollView{
if(self.collectionView == scrollView){
CGFloat width = KScreenWidth - kGetScaleWidth(16);
int x = (int)(scrollView.contentOffset.x / width);
if(x < self.gameArray.count){
self.pageControl.curPage = x;
}
}
}
#pragma mark - XPSessionMessageGameInfoView
- (void)clicTokMineUserInfo{
XPMineUserInfoViewController * infoVC = [[XPMineUserInfoViewController alloc] init];
infoVC.uid = self.userInfo.uid;
[self.getKeyWindowNav pushViewController:infoVC animated:YES];
}
#pragma mark - SessionNavViewDelegate
- (void)sessionNavView:(SessionNavView *)view didClickLike:(UIButton *)sender {
[self.presenter attentionUser:self.session.sessionId];
}
- (void)sessionNavView:(SessionNavView *)view didClickBack:(UIButton *)sender {
if (self.openType == SessionListOpenTypeRoom) {
CATransition *transition = [CATransition animation];
transition.duration = 0.3f;
transition.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
transition.type = kCATransitionPush;
transition.subtype = kCATransitionFromLeft;
[self.view.superview.layer addAnimation:transition forKey:nil];
[self removeFromParentViewController];
[self.view removeFromSuperview];
return;
}
[self.navigationController popViewControllerAnimated:YES];
}
- (void)sessionNavView:(SessionNavView *)view didClickReport:(UIButton *)sender {
SessionInfoViewController * reportVC = [[SessionInfoViewController alloc] init];
reportVC.userId = self.session.sessionId;
[self.getKeyWindowNav pushViewController:reportVC animated:YES];
}
///跟随房间
- (void)sessionNavView:(SessionNavView *)view didClickToRoom:(UIButton *)sender{
if(self.userInfo.uid > 0){
if (self.openType != SessionListOpenTypeRoom) {
__block BOOL isSameRoom = NO;
__block RoomInfoModel *roomModel;
[self.getKeyWindowNav.viewControllers enumerateObjectsUsingBlock:^(__kindof UIViewController * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
if ([obj isKindOfClass:[XPRoomViewController class]]) {
XPRoomViewController<RoomHostDelegate> * rooomVC = obj;
[[self getKeyWindowNav] popToRootViewControllerAnimated:NO];
roomModel = rooomVC.getRoomInfo;
if(rooomVC.getRoomInfo.uid == self.userInfo.uid) {
isSameRoom = YES;
} else {
[rooomVC exitRoom];
}
*stop = YES;
}
}];
if (!isSameRoom) {
if (roomModel.type == RoomType_MiniGame) {
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
[XPRoomViewController openRoom:@(self.userInfo.uid).stringValue fromNick:self.userInfo.nick fromType:UserEnterRoomFromType_Follow_User fromUid:[NSString stringWithFormat:@"%ld", self.userInfo.uid] viewController:[[XCCurrentVCStackManager shareManager] getCurrentVC]];
});
} else {
[XPRoomViewController openRoom:@(self.userInfo.uid).stringValue fromNick:self.userInfo.nick fromType:UserEnterRoomFromType_Follow_User fromUid:[NSString stringWithFormat:@"%ld", self.userInfo.uid] viewController:self];
}
}
}
}
}
#pragma mark - UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return self.messages.count;
}
- (nonnull UITableViewCell *)tableView:(nonnull UITableView *)tableView cellForRowAtIndexPath:(nonnull NSIndexPath *)indexPath {
NIMMessage * message = [self.messages safeObjectAtIndex1:indexPath.row];
NSString * identifier = [MessageCell cellContent:message];
///从复用池中获取所需要的cell
MessageCell * cell = [tableView dequeueReusableCellWithIdentifier:identifier];
if (!cell) {
///如果没有的话 根据identifier 注册一下 重新获取一下即可
[tableView registerClass:[MessageCell class] forCellReuseIdentifier:identifier];
///如果注册过了 就不需要判断cell是否为空
cell = [tableView dequeueReusableCellWithIdentifier:identifier];
}
cell.delegate = self;
[cell renderWithMessage:[self.messages safeObjectAtIndex1:indexPath.row]];
return cell;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
NIMMessage *msg = [self.messages safeObjectAtIndex1:indexPath.row];
return [MessageCell measureHeight:msg];
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
}
#pragma mark - XPMineGameOrderDetailsViewDelegate
///再次邀请
-(void)againinitiateInvitationWithGameInfo:(UserGameInfoVo *)gameInfo{
XPMinePlaceOrderView *orderVeiw = [[XPMinePlaceOrderView alloc]initWithFrame:CGRectMake(0, 0, KScreenWidth, KScreenHeight)];
for (int i = 0; i < self.gameArray.count; i++) {
UserGameInfoVo *model = self.gameArray[i];
if([model.gameId isEqualToString:gameInfo.gameId]){
orderVeiw.selectGameInfo = model;
}
}
orderVeiw.inning = gameInfo.inning;
orderVeiw.diamonds = self.diamonds;
orderVeiw.gameList = self.gameArray;
orderVeiw.delegate = self;
[self.view addSubview:orderVeiw];
}
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
[self.toolbarView foldMenuView];
}
#pragma mark - NIMChatManagerDelegate
- (void)onRecvMessages:(NSArray<NIMMessage *> *)messages {
NIMMessage *message = messages.firstObject;
NIMSession *session = message.session;
if (![session isEqual:self.session] || !messages.count) {
return;
}
for (NIMMessage *message in messages) {
if (message.isDeleted) {
continue;
}
[self.messages addObject:message];
}
[self.sessionTableView reloadData];
[self.sessionTableView nim_scrollToBottom:YES];
[[NIMSDK sharedSDK].conversationManager markAllMessagesReadInSession:self.session];
}
- (void)onRecvRevokeMessageNotification:(NIMRevokeMessageNotification *)notification{
[[NIMSDK sharedSDK].conversationManager deleteMessage:notification.message];
}
- (void)sendMessage:(NIMMessage *)message didCompleteWithError:(NSError *)error {
if (message.session.sessionType != NIMSessionTypeP2P) {
return;
}
if (![self isExistMessages:message]) {
[self.messages addObject:message];
}
if (message.yidunAntiSpamRes) {
NSDictionary * spamRes = message.yidunAntiSpamRes.toJSONObject;
NSDictionary * spamResExt = ((NSString *)spamRes[@"ext"]).toJSONObject;
if ([spamResExt[@"antispam"][@"suggestion"] intValue] == 2) {
NSDictionary * dic = @{@"suggestion": @"2"};
message.localExt = dic;
[[NIMSDK sharedSDK].conversationManager updateMessage:message forSession:self.session completion:nil];
}
}
[self.sessionTableView reloadData];
[self.sessionTableView nim_scrollToBottom:YES];
}
- (void)fetchMessageAttachment:(NIMMessage *)message didCompleteWithError:(NSError *)error {
if (![message.session isEqual:self.session]) return;
for (NIMMessage * msg in self.messages) {
if ([msg.messageId isEqualToString:message.messageId]) {
NSInteger index = [self.messages indexOfObject:msg];
[self.messages replaceObjectAtIndex:index withObject:message];
[self.sessionTableView reloadRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:index inSection:0]] withRowAnimation:UITableViewRowAnimationNone];
break;
}
}
}
#pragma mark - NIMConversationManagerDelegate
- (void)messagesDeletedInSession:(NIMSession *)session {
[self.messages removeAllObjects];
[self initData];
}
#pragma mark - XPSessionMessageGameCellDelegate
///点击头像
- (void)xpSessionMessageGameCell:(XPSessionMessageGameCell *)cell onAvatarClick:(NSInteger)uid{
if ([[ClientConfig shareConfig].configInfo.officialMsgUids containsObject:self.session.sessionId] || [[ClientConfig shareConfig].configInfo.officialAccountUids containsObject:self.session.sessionId]) {
return;
}
if (self.openType != SessionListOpenTypeRoom) {
XPMineUserInfoViewController * infoVC = [[XPMineUserInfoViewController alloc] init];
infoVC.uid = uid;
[self.getKeyWindowNav pushViewController:infoVC animated:YES];
}
}
///跟随房间
- (void)xpSessionMessageGameCell:(XPSessionMessageGameCell *)cell onFollowInRoom:(NSString *)roomUid{
if (self.openType != SessionListOpenTypeRoom) {
__block BOOL isSameRoom = NO;
__block RoomInfoModel *roomModel;
[self.getKeyWindowNav.viewControllers enumerateObjectsUsingBlock:^(__kindof UIViewController * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
if ([obj isKindOfClass:[XPRoomViewController class]]) {
XPRoomViewController<RoomHostDelegate> * rooomVC = obj;
[[self getKeyWindowNav] popToRootViewControllerAnimated:NO];
roomModel = rooomVC.getRoomInfo;
if(rooomVC.getRoomInfo.uid == [roomUid integerValue]) {
isSameRoom = YES;
} else {
[rooomVC exitRoom];
}
*stop = YES;
}
}];
if (!isSameRoom) {
if (roomModel.type == RoomType_MiniGame) {
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
[XPRoomViewController openRoom:roomUid fromNick:self.userInfo.nick fromType:UserEnterRoomFromType_Follow_User fromUid:[NSString stringWithFormat:@"%ld", self.userInfo.uid] viewController:[[XCCurrentVCStackManager shareManager] getCurrentVC]];
});
} else {
[XPRoomViewController openRoom:roomUid fromNick:self.userInfo.nick fromType:UserEnterRoomFromType_Follow_User fromUid:[NSString stringWithFormat:@"%ld", self.userInfo.uid] viewController:self];
}
}
}
}
///下单
- (void)xpSessionMessageGameCell:(XPSessionMessageGameCell *)cell onPlaceOrder:(NSString *)uid{
XPMinePlaceOrderView *orderVeiw = [[XPMinePlaceOrderView alloc]initWithFrame:CGRectMake(0, 0, KScreenWidth, KScreenHeight)];
orderVeiw.diamonds = self.diamonds;
orderVeiw.selectGameInfo = cell.gameInfo;
orderVeiw.gameList = self.userInfo.userGamePartner;
orderVeiw.delegate = self;
[self.view addSubview:orderVeiw];
}
- (void)xpSessionMessageGameCell:(XPSessionMessageGameCell *)cell chooseGame:(nonnull NSString *)uid{
XPMineUserInfoViewController * infoVC = [[XPMineUserInfoViewController alloc] initWithChooseGame];
infoVC.uid = self.userInfo.uid;
[[self getKeyWindowNav] pushViewController:infoVC animated:YES];
}
#pragma mark - XPMinePlaceOrderViewDelegate
///发起邀请
-(void)initiateInvitationWithGameInfo:(UserGameInfoVo *)gameInfo count:(NSString *)count{
[self showLoading];
[Api sendInitiateInvitationGame:^(BaseModel * _Nullable data, NSInteger code, NSString * _Nullable msg) {
[self hideHUD];
if(code == 200){
[self sendInitiateInvitationGameSuccess];
return;
}
[self showErrorToast:msg];
} gameId:gameInfo.gameId gameUid:gameInfo.uid inning:count uid:[AccountInfoStorage instance].getUid];
}
///充值
-(void)payHandleWithShowView:(BOOL)isShow{
if(isShow == YES){
TTAlertConfig *config = [[TTAlertConfig alloc] init];
config.title = @"提示";
config.actionStyle = TTAlertActionConfirmStyle;
config.message = [NSString stringWithFormat:@"余额不足,请充值"];
TTAlertButtonConfig *confirmButtonConfig = [[TTAlertButtonConfig alloc]init];
confirmButtonConfig.title = @"去充值";
config.confirmButtonConfig = confirmButtonConfig;
confirmButtonConfig.titleColor = UIColorFromRGB(0x2B2D33);
confirmButtonConfig.backgroundColor = UIColorFromRGB(0xFFDA24);
confirmButtonConfig.font = [UIFont systemFontOfSize:14 weight:UIFontWeightMedium];
confirmButtonConfig.cornerRadius = 38/2;
[TTPopup alertWithConfig:config confirmHandler:^{
XPMineNewRechargeViewController *payVC = [[XPMineNewRechargeViewController alloc]init];
[self.navigationController pushViewController:payVC animated:YES];
} cancelHandler:^{
}];
return;
}
XPMineNewRechargeViewController *payVC = [[XPMineNewRechargeViewController alloc]init];
[self.navigationController pushViewController:payVC animated:YES];
}
-(void)sendInitiateInvitationGameSuccess{
[self showSuccessToast:@"邀请成功"];
[[NSNotificationCenter defaultCenter]postNotificationName:@"kGameOrderListRefreshData" object:nil];
}
- (void)didFailRetry:(NIMMessage *)message {
if (message.isReceivedMsg) {
[[NIMSDK sharedSDK].chatManager fetchMessageAttachment:message error:nil];
} else {
[[NIMSDK sharedSDK].chatManager resendMessage:message error:nil];
}
}
#pragma mark - MessageToolbarViewDelegate
- (void)keyboardWillChangeFrame:(CGRect)rect {
CGFloat heightFromBottom = rect.size.height;
heightFromBottom = MAX(0.0, heightFromBottom);
[self.toolbarView mas_updateConstraints:^(MASConstraintMaker *make) {
make.bottom.mas_equalTo(self.view).offset(-heightFromBottom);
}];
[self.sessionTableView nim_scrollToBottom:NO];
}
- (void)sendTextMessage:(NSString *)text {
NIMMessage *message = [NIMMessageMaker msgWithText:text];
[[[NIMSDK sharedSDK] chatManager] sendMessage:message toSession:self.session error:nil];
}
- (void)didSelectMenuItem:(MessageMenuModel *)info {
UIWindow * currentWindow;
for (int i = 0; i < [UIApplication sharedApplication].windows.count; i++) {
UIWindow * window = [[UIApplication sharedApplication].windows safeObjectAtIndex1:i];
if(window.tag == 1000) {
currentWindow = window;
break;
}
}
if (currentWindow) {
currentWindow.windowLevel = -1;
}
switch (info.type) {
case MessageMenuType_Photo:
{
TZImagePickerController *imagePickerVc = [[TZImagePickerController alloc] initWithMaxImagesCount:1 delegate:self];
imagePickerVc.modalPresentationStyle = UIModalPresentationOverFullScreen;
imagePickerVc.allowPickingVideo = NO;
imagePickerVc.allowTakeVideo = NO;
imagePickerVc.naviBgColor = [ThemeColor appCellBackgroundColor];
imagePickerVc.naviTitleColor = [ThemeColor mainTextColor];
imagePickerVc.barItemTextColor = [ThemeColor mainTextColor];
[self presentViewController:imagePickerVc animated:YES completion:nil];
}
break;
case MessageMenuType_Gift:
{
XPSendGiftView * giftView = [[XPSendGiftView alloc] initWithType:SendGiftType_User uid:nil];
XPGiftUserInfoModel * userModel = [[XPGiftUserInfoModel alloc] init];
userModel.avatar = self.userInfo.avatar;
userModel.nick = self.userInfo.nick;
userModel.uid = self.session.sessionId.integerValue;
userModel.isSelect = YES;
[giftView configGiftUsers:@[userModel]];
[self presentViewController:giftView animated:YES completion:nil];
}
break;
default:
break;
}
}
- (void)audioRecordCompletion:(NSString *)recordPath {
NIMMessage *message = [NIMMessageMaker msgWithAudio:recordPath];
[[[NIMSDK sharedSDK] chatManager] sendMessage:message toSession:self.session error:nil];
}
#pragma mark - TZImagePickerControllerDelegate
- (void)imagePickerController:(TZImagePickerController *)picker didFinishPickingPhotos:(NSArray<UIImage *> *)photos sourceAssets:(NSArray *)assets isSelectOriginalPhoto:(BOOL)isSelectOriginalPhoto infos:(NSArray<NSDictionary *> *)infos {
[photos enumerateObjectsUsingBlock:^(UIImage * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
if (obj) {
// 构造出具体会话
NIMMessage * message = [NIMMessageMaker msgWithImage:obj];
// 发送消息
[[NIMSDK sharedSDK].chatManager sendMessage:message toSession:self.session error:nil];
}
}];
}
#pragma mark - SessionRiskViewDelegate
- (void)sessionRiskViewCloseButtonClick:(SessionRiskView *)view {
[[SessionRiskCache shareCache] saveCloseRisk:self.session.sessionId];
self.riskAlertView.hidden = YES;
self.emptyVeiw.hidden = NO;
}
#pragma mark - Getters And Setters
- (NSArray<NIMMessage *> *)messages {
if (!_messages) {
_messages = [[NSMutableArray alloc] init];
}
return _messages;
}
#pragma mark - Event Response
- (void)closeKeyBoard {
[self.view endEditing:YES];
[self.toolbarView foldMenuView];
}
- (UITableView *)sessionTableView {
if (!_sessionTableView) {
_sessionTableView = [[UITableView alloc] init];
_sessionTableView.delegate = self;
_sessionTableView.dataSource = self;
_sessionTableView.backgroundColor = UIColor.clearColor;
_sessionTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
_sessionTableView.showsVerticalScrollIndicator = NO;
// UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(closeKeyBoard)];
// [_sessionTableView addGestureRecognizer:tap];
}
return _sessionTableView;
}
- (SessionToolbarView *)toolbarView {
if (!_toolbarView) {
_toolbarView = [[SessionToolbarView alloc] init];
_toolbarView.delegate = self;
_toolbarView.sendDisabled = YES;
}
return _toolbarView;
}
- (SessionNavView *)sessionNavView {
if (!_sessionNavView) {
_sessionNavView = [[SessionNavView alloc] init];
_sessionNavView.delegate = self;
}
return _sessionNavView;
}
- (SessionRiskView *)riskAlertView {
if (!_riskAlertView) {
_riskAlertView = [[SessionRiskView alloc] init];
_riskAlertView.delegate = self;
_riskAlertView.hidden = YES;
}
return _riskAlertView;
}
- (UICollectionView *)collectionView{
if (!_collectionView) {
UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
layout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
layout.minimumLineSpacing = 0;
layout.minimumInteritemSpacing = 0;
layout.sectionInset = UIEdgeInsetsMake(0, 0, 0, 0);
_collectionView = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:layout];
_collectionView.dataSource = self;
_collectionView.delegate = self;
_collectionView.pagingEnabled = YES;
_collectionView.hidden = YES;
_collectionView.backgroundColor = [UIColor clearColor];
_collectionView.showsHorizontalScrollIndicator = NO;
[_collectionView registerClass:[XPSessionMessageGameCell class] forCellWithReuseIdentifier:NSStringFromClass([XPSessionMessageGameCell class])];
[_collectionView registerClass:[XPSessionMessageGameInfoView class] forSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:NSStringFromClass([XPSessionMessageGameInfoView class])];
}
return _collectionView;
}
- (XPSessionMessageGamePageControl *)pageControl{
if(!_pageControl){
_pageControl = [[XPSessionMessageGamePageControl alloc]initWithFrame:CGRectZero];
_pageControl.hidden = YES;
}
return _pageControl;
}
- (UIStackView *)stackView {
if (!_stackView) {
_stackView = [[UIStackView alloc] init];
_stackView.axis = UILayoutConstraintAxisVertical;
_stackView.distribution = UIStackViewDistributionFill;
_stackView.alignment = UIStackViewAlignmentFill;
_stackView.spacing = kGetScaleWidth(8);
}
return _stackView;
}
- (UIView *)emptyVeiw{
if(!_emptyVeiw){
_emptyVeiw = [[UIView alloc]initWithFrame:CGRectZero];
_emptyVeiw.hidden = YES;
_emptyVeiw.backgroundColor = [UIColor clearColor];
}
return _emptyVeiw;
}
@end