Files
yinmeng-ios/xplan-ios/Main/Room/View/MenuContainerView/XPRoomSendTextView.m
2024-05-14 18:25:14 +08:00

320 lines
12 KiB
Objective-C

//
// XPRoomSendTextView.m
// xplan-ios
//
// Created by 冯硕 on 2021/10/29.
//
#import "XPRoomSendTextView.h"
///Third
#import <Masonry/Masonry.h>
#import <NIMSDK/NIMSDK.h>
#import "NSObject+MJExtension.h"
#import <IQKeyboardManager/IQKeyboardManager.h>
///Tool
#import "ThemeColor+Room.h"
#import "XPMacro.h"
#import "UIImage+Utils.h"
#import "XPConstant.h"
#import "AccountInfoStorage.h"
#import "NSMutableDictionary+Saft.h"
///Model
#import "XPMessageRemoteExtModel.h"
#import "UserInfoModel.h"
#import "RoomInfoModel.h"
//公屏限制最大字数
#define MAX_STARWORDS_LENGTH 300
@interface XPRoomSendTextView ()<UITextFieldDelegate>
///
@property (nonatomic,strong) UIStackView *stackView;
///输入框
@property (nonatomic, strong) UITextField *editTextFiled;
///发送按钮
@property (nonatomic, strong) UIButton *sendButton;
///文本输入的内容
@property (nonatomic,copy) NSString *inputMessage;
///代理
@property (nonatomic,weak) id<RoomHostDelegate> delegate;
///被@的人的数组 such as:@["'@小明','"@小红']
@property (nonatomic, strong) NSMutableArray *atNames;
///被@的人的uid 需要跟上面的名字对应位置
@property (nonatomic, strong) NSMutableArray *atUids;
@end
@implementation XPRoomSendTextView
- (void)dealloc {
[[NSNotificationCenter defaultCenter] removeObserver:self];
}
- (instancetype)initWithDelegate:(id<RoomHostDelegate>)delegate {
self = [super initWithFrame:CGRectMake(0, KScreenHeight - 40, KScreenWidth, 40)];
if (self) {
self.delegate = delegate;
[self addNotification];
[self initSubViews];
[self initSubViewConstraints];
[IQKeyboardManager sharedManager].enable = NO;
}
return self;
}
#pragma mark - Response
- (void)sendButtonDidClick:(UIButton *)sender {
UserInfoModel * userInfo = [self.delegate getUserInfo];
XPMessageRemoteExtModel *extModel = [[XPMessageRemoteExtModel alloc] init];
extModel.defUser = userInfo.defUser;
extModel.erbanNo = userInfo.erbanNo;
extModel.carName = userInfo.carName;
extModel.inRoomNameplatePic = userInfo.nameplatePic;
extModel.inRoomNameplateWord = userInfo.nameplateWord;
extModel.charmUrl = userInfo.userLevelVo.charmUrl;
extModel.experLevelSeq = userInfo.userLevelVo.experLevelSeq;
extModel.experUrl = userInfo.userLevelVo.experUrl;
extModel.newUser = userInfo.newUser;
extModel.vipIcon = userInfo.userVipInfoVO.vipIcon;
extModel.androidBubbleUrl = userInfo.androidBubbleUrl;
extModel.iosBubbleUrl = userInfo.iosBubbleUrl;
extModel.fromSayHelloChannel = userInfo.fromSayHelloChannel;
NIMMessage * message = [[NIMMessage alloc] init];
message.text = self.inputMessage;
NSMutableDictionary *remoteExt = [NSMutableDictionary dictionaryWithObject:extModel.model2dictionary forKey:[AccountInfoStorage instance].getUid];
//查找消息中是否有@人
NSMutableArray *nickArray = [NSMutableArray array];
NSMutableArray *uidArray = [NSMutableArray array];
for (int i = 0; i<self.atNames.count; i++) {
NSString *nick = self.atNames[i];
if ([self.editTextFiled.text containsString:nick]) {
if ([nickArray containsObject:nick]) {
continue;
} else {
[nickArray addObject:nick];
[uidArray addObject:self.atUids[i]];
}
}
}
id uidStr = [uidArray toJSONObject];
id nickStr = [nickArray toJSONObject];
[remoteExt safeSetObject:uidStr forKey:@"atUids"];
[remoteExt safeSetObject:nickStr forKey:@"atNames"];
message.remoteExt = remoteExt;
///网易易盾 拦截高风险
NIMAntiSpamOption *option = [[NIMAntiSpamOption alloc]init];
option.yidunEnabled = YES;
option.businessId = KeyWithType(keyType_YiDunBussinessId);
message.antiSpamOption = option;
NSString * sessionId = [NSString stringWithFormat:@"%ld", [self.delegate getRoomInfo].roomId];
//构造会话
NIMSession *session = [NIMSession session:sessionId type:NIMSessionTypeChatroom];
[[NIMSDK sharedSDK].chatManager sendMessage:message toSession:session completion:^(NSError * _Nullable error) {
self.editTextFiled.text = @"";
[self.editTextFiled resignFirstResponder];
[self.atUids removeAllObjects];
[self.atNames removeAllObjects];
self.inputMessage = nil;
}];
}
- (void)keyboardWillShow:(NSNotification *)notification {
[self.superview bringSubviewToFront:self];
NSDictionary *info = [notification userInfo];
NSValue *value = [info objectForKey:UIKeyboardFrameEndUserInfoKey];
CGFloat keyBoardEndY = value.CGRectValue.origin.y;
NSNumber *curve = [info objectForKey:UIKeyboardAnimationCurveUserInfoKey];
CGFloat duration = [[info objectForKey:UIKeyboardAnimationDurationUserInfoKey] floatValue];
CGRect endKeyboardRect = [[info objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue];
CGFloat h = endKeyboardRect.size.height;
[UIView animateWithDuration:duration animations:^{
[self mas_remakeConstraints:^(MASConstraintMaker *make) {
make.left.right.equalTo(self.superview);
make.height.equalTo(@40);
make.bottom.equalTo(self.superview).offset(-h);
}];
[UIView setAnimationBeginsFromCurrentState:YES];
[UIView setAnimationCurve:[curve intValue]];
self.center = CGPointMake(self.center.x, keyBoardEndY - statusbarHeight - self.bounds.size.height/2.0);
}];
}
//键盘隐藏
- (void)keyboardWillHidden:(NSNotification *)notification {
NSDictionary *info = [notification userInfo];
CGFloat duration = [[info objectForKey:UIKeyboardAnimationDurationUserInfoKey] floatValue];
[UIView animateWithDuration:duration animations:^{
[self mas_remakeConstraints:^(MASConstraintMaker *make) {
make.bottom.left.right.equalTo(self.superview);
make.height.equalTo(@40);
}];
self.hidden = YES;
}];
}
-(void)textFieldEditChanged:(NSNotification *)notification{
UITextField *textField = (UITextField *)notification.object;
NSString *toBeString = textField.text;
NSString *lang = [textField.textInputMode primaryLanguage];
if ([lang isEqualToString:@"zh-Hans"]){// 简体中文输入
//获取高亮部分
UITextRange *selectedRange = [textField markedTextRange];
UITextPosition *position = [textField positionFromPosition:selectedRange.start offset:0];
// 没有高亮选择的字,则对已输入的文字进行字数统计和限制
if (!position){
if (toBeString.length > MAX_STARWORDS_LENGTH){
NSRange rangeIndex = [toBeString rangeOfComposedCharacterSequenceAtIndex:MAX_STARWORDS_LENGTH];
if (rangeIndex.length == 1){
textField.text = [toBeString substringToIndex:MAX_STARWORDS_LENGTH];
}else{
NSRange rangeRange = [toBeString rangeOfComposedCharacterSequencesForRange:NSMakeRange(0, MAX_STARWORDS_LENGTH)];
textField.text = [toBeString substringWithRange:rangeRange];
}
}
}
}else{ // 中文输入法以外的直接对其统计限制即可,不考虑其他语种情况
if (toBeString.length > MAX_STARWORDS_LENGTH){
NSRange rangeIndex = [toBeString rangeOfComposedCharacterSequenceAtIndex:MAX_STARWORDS_LENGTH];
if (rangeIndex.length == 1){
textField.text = [toBeString substringToIndex:MAX_STARWORDS_LENGTH];
}else{
NSRange rangeRange = [toBeString rangeOfComposedCharacterSequencesForRange:NSMakeRange(0, MAX_STARWORDS_LENGTH)];
textField.text = [toBeString substringWithRange:rangeRange];
}
}
}
self.inputMessage = textField.text;
if (self.inputMessage.length > 0) {
self.sendButton.enabled = YES;
} else {
self.sendButton.enabled = NO;
}
}
- (BOOL)textFieldShouldReturn:(UITextField *)textField{
[self.editTextFiled resignFirstResponder];
return YES;
}
#pragma mark - Public Method
+ (instancetype)showTextView:(UIView *)view delegate:(id<RoomHostDelegate>)delegate atUid:(NSString *)uid atNick:(NSString *)nick {
__block XPRoomSendTextView * textView;
[view.subviews enumerateObjectsUsingBlock:^(__kindof UIView * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
if ([obj isKindOfClass:[XPRoomSendTextView class]]) {
textView = obj;
*stop = YES;
}
}];
if (textView == nil) {
textView = [[XPRoomSendTextView alloc] initWithDelegate:delegate];
[view addSubview:textView];
}
textView.hidden = NO;
if(textView.superview == nil ){
[view addSubview:textView];
}
[textView mas_makeConstraints:^(MASConstraintMaker *make) {
make.left.right.bottom.mas_equalTo(view);
make.height.mas_equalTo(40);
}];
[textView.editTextFiled becomeFirstResponder];
if (nick) {
[textView.atUids addObject:uid];
[textView.atNames addObject:[NSString stringWithFormat:@"@%@", nick]];
textView.editTextFiled.text = [NSString stringWithFormat:@"%@@%@\u2004", textView.editTextFiled.text, nick];
textView.inputMessage = textView.editTextFiled.text;
textView.sendButton.enabled = YES;
}
return textView;
}
#pragma mark - Private Method
- (void)initSubViews {
self.backgroundColor = [ThemeColor appBackgroundColor];
[self addSubview:self.stackView];
[self.stackView addArrangedSubview:self.editTextFiled];
[self.stackView addArrangedSubview:self.sendButton];
}
- (void)initSubViewConstraints {
[self.stackView mas_makeConstraints:^(MASConstraintMaker *make) {
make.left.mas_equalTo(self).offset(8);
make.right.mas_equalTo(self).offset(-5);
make.top.bottom.mas_equalTo(self);
}];
[self.sendButton mas_makeConstraints:^(MASConstraintMaker *make) {
make.width.mas_equalTo(50);
make.top.bottom.mas_equalTo(self).inset(5);
}];
}
- (void)addNotification {
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHidden:) name:UIKeyboardWillHideNotification object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textFieldEditChanged:) name:UITextFieldTextDidChangeNotification object:self.editTextFiled];
}
#pragma mark - Getters And Setters
- (UITextField *)editTextFiled{
if (!_editTextFiled) {
_editTextFiled = [[UITextField alloc] init];
NSAttributedString * attribute = [[NSAttributedString alloc] initWithString:@"请输入消息..." attributes:@{NSFontAttributeName : [UIFont systemFontOfSize:15], NSForegroundColorAttributeName : [ThemeColor secondTextColor]}];
_editTextFiled.attributedPlaceholder = attribute;
_editTextFiled.borderStyle = UITextBorderStyleNone;
_editTextFiled.returnKeyType = UIReturnKeyDone;
_editTextFiled.textColor = [ThemeColor alertTitleColor];
_editTextFiled.font = [UIFont systemFontOfSize:15];
_editTextFiled.delegate = self;
[_editTextFiled setContentHuggingPriority:UILayoutPriorityDefaultLow forAxis:UILayoutConstraintAxisHorizontal];
}
return _editTextFiled;
}
- (UIButton *)sendButton{
if (!_sendButton) {
_sendButton = [[UIButton alloc] init];
[_sendButton setTitle:@"发送" forState:UIControlStateNormal];
_sendButton.titleLabel.textColor = [ThemeColor mainTextColor];
_sendButton.titleLabel.font = [UIFont systemFontOfSize:15];
[_sendButton setBackgroundImage:[UIImage imageWithColor:[ThemeColor disableButtonColor] ]forState:UIControlStateDisabled];
[_sendButton setBackgroundImage:[UIImage gradientColorImageFromColors:@[[ThemeColor confirmButtonGradientStartColor], [ThemeColor confirmButtonGradientEndColor]] gradientType:GradientTypeLeftToRight imgSize:CGSizeMake(10, 10)] forState:UIControlStateNormal];
_sendButton.enabled = NO;
_sendButton.layer.cornerRadius = 5.0;
_sendButton.layer.masksToBounds = YES;
[_sendButton addTarget:self action:@selector(sendButtonDidClick:) forControlEvents:UIControlEventTouchUpInside];
}
return _sendButton;
}
- (UIStackView *)stackView {
if (!_stackView) {
_stackView = [[UIStackView alloc] init];
_stackView.axis = UILayoutConstraintAxisHorizontal;
_stackView.distribution = UIStackViewDistributionFill;
_stackView.alignment = UIStackViewAlignmentCenter;
_stackView.spacing = 10;
}
return _stackView;
}
- (NSMutableArray *)atNames {
if (!_atNames) {
_atNames = [NSMutableArray array];
}
return _atNames;
}
- (NSMutableArray *)atUids {
if (!_atUids) {
_atUids = [NSMutableArray array];
}
return _atUids;
}
@end