Files
peko-ios/YuMi/Modules/YMRoom/View/MenuContainerView/XPRoomSendTextView.m
eggmanQQQ 8adb50763d #1217
修正 bugs
2024-07-05 11:16:18 +08:00

418 lines
17 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 "UIImage+Utils.h"
#import "AccountInfoStorage.h"
///Model
#import "XPMessageRemoteExtModel.h"
#import "UserInfoModel.h"
#import "RoomInfoModel.h"
#import "ClientConfig.h"
//公屏限制最大字数
#define MAX_STARWORDS_LENGTH 300
@interface XPRoomSendTextView () <NIMChatManagerDelegate>
///输入框
@property (nonatomic, strong) MSBaseTextField *editTextFiled;
@property (nonatomic, strong) UIView *bgEditTextFiled;
///发送按钮
@property (nonatomic, strong) UIButton *sendButton;
///上头像
@property(nonatomic,strong) UIButton *headlineBtn;
///文本输入的内容
@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 - 60, KScreenWidth, 60)];
if (self) {
self.delegate = delegate;
[[NIMSDK sharedSDK].chatManager addDelegate:self];
[self addNotification];
[self initSubViews];
[self initSubViewConstraints];
[IQKeyboardManager sharedManager].enable = NO;
}
return self;
}
- (void)sendMessage:(NIMMessage *)message didCompleteWithError:(NSError *)error {
}
#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.isCustomWord = userInfo.isCustomWord;
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;
if([self.delegate getPublicScreenType]==1){
extModel.avatar = userInfo.avatar;
extModel.nick = userInfo.nick;
NSString * headwearUrl= userInfo.headwearEffect.length > 0 ? userInfo.headwearEffect : userInfo.headwearPic;
extModel.headwearUrl = headwearUrl;
}
NIMMessage * message = [[NIMMessage alloc] init];
message.text = self.inputMessage;
NSMutableDictionary *remoteExt = [NSMutableDictionary dictionaryWithObject:extModel.model2dictionary forKey:[AccountInfoStorage instance].getUid];
if([self.delegate getPublicScreenType] == 0){
//查找消息中是否有@人
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 setObject:uidStr forKey:@"atUids"];
[remoteExt setObject:nickStr forKey:@"atNames"];
}
message.remoteExt = remoteExt;
///网易易盾 拦截高风险
NIMAntiSpamOption *option = [[NIMAntiSpamOption alloc]init];
option.yidunEnabled = YES;
option.businessId = KeyWithType(keyType_YiDunBussinessId);
option.content = [NSString stringWithFormat:@"{\"type\": 1, \"data\": \"天安门\"}"];
message.antiSpamOption = option;
NSString *publicChatRoomId = [NSString stringWithFormat:@"%@",[ClientConfig shareConfig].configInfo.publicChatRoomIdMap[userInfo.partitionId]];
NSString * sessionId = [self.delegate getPublicScreenType] == 0 ? [NSString stringWithFormat:@"%ld", [self.delegate getRoomInfo].roomId]:publicChatRoomId;
//构造会话
self.sendButton.enabled = NO;
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)showSendheadlineBtnAction{
if(self.editTextFiled.text.length == 0){
[XNDJTDDLoadingTool showErrorWithMessage:YMLocalizedString(@"MSSessionReleaseHeadlinesView0")];
return;
}
if(self.editTextFiled.text.length > 100){
[XNDJTDDLoadingTool showErrorWithMessage:YMLocalizedString(@"MSSessionReleaseHeadlinesView0")];
return;
}
[self.editTextFiled resignFirstResponder];
[[NSNotificationCenter defaultCenter]postNotificationName:@"kShowSendheadlineView" object:self.editTextFiled.text];
self.editTextFiled.text = @"";
}
- (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:^{
if(self.superview){
[self mas_remakeConstraints:^(MASConstraintMaker *make) {
make.leading.trailing.equalTo(self.superview);
make.height.equalTo(@60);
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.leading.trailing.equalTo(self.superview);
make.height.equalTo(@60);
}];
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;
}
}
#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];
}else{
UIButton *headlineBtn = [textView viewWithTag:100];
UIButton *sendButton = [textView viewWithTag:101];
if(delegate.getPublicScreenType == 0){
headlineBtn.hidden = YES;
[sendButton mas_remakeConstraints:^(MASConstraintMaker *make) {
make.width.mas_equalTo(58);
make.height.mas_equalTo(29);
make.trailing.mas_equalTo(-15);
make.centerY.equalTo(textView);
}];
}else{
[sendButton mas_remakeConstraints:^(MASConstraintMaker *make) {
make.width.mas_equalTo(58);
make.height.mas_equalTo(29);
make.trailing.mas_equalTo(-53);
make.centerY.equalTo(textView);
}];
headlineBtn.hidden = NO;
}
}
textView.hidden = NO;
[textView mas_makeConstraints:^(MASConstraintMaker *make) {
make.leading.trailing.bottom.mas_equalTo(view);
make.height.mas_equalTo(60);
}];
[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 = UIColorFromRGB(0x260159);
[self addSubview:self.bgEditTextFiled];
[self.bgEditTextFiled addSubview:self.editTextFiled];
[self addSubview:self.sendButton];
[self addSubview:self.headlineBtn];
}
- (void)initSubViewConstraints {
[self.headlineBtn mas_makeConstraints:^(MASConstraintMaker *make) {
make.width.mas_equalTo(50);
make.height.mas_equalTo(45);
make.trailing.mas_equalTo(0);
make.centerY.equalTo(self);
}];
[self.bgEditTextFiled mas_makeConstraints:^(MASConstraintMaker *make) {
make.leading.mas_equalTo(6);
make.height.mas_equalTo(36);
make.top.mas_equalTo(12);
make.trailing.equalTo(self.sendButton.mas_leading).mas_offset(-8);
}];
[self.editTextFiled mas_makeConstraints:^(MASConstraintMaker *make) {
make.leading.mas_equalTo(20);
make.trailing.mas_equalTo(-kGetScaleWidth(20));
make.top.bottom.mas_equalTo(0);
}];
if(self.delegate.getPublicScreenType == 0){
self.headlineBtn.hidden = YES;
[self.sendButton mas_remakeConstraints:^(MASConstraintMaker *make) {
make.width.mas_equalTo(58);
make.height.mas_equalTo(29);
make.trailing.mas_equalTo(-15);
make.centerY.equalTo(self);
}];
return;
}
[self.sendButton mas_remakeConstraints:^(MASConstraintMaker *make) {
make.width.mas_equalTo(58);
make.height.mas_equalTo(29);
make.trailing.mas_equalTo(-53);
make.centerY.equalTo(self);
}];
self.headlineBtn.hidden = NO;
}
- (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];
}
-(void)showInputView:(NSString *)text{
self.editTextFiled.text = text;
self.inputMessage = text;
if(text.length > 0){
self.sendButton.enabled = YES;
}
}
#pragma mark - Getters And Setters
- (MSBaseTextField *)editTextFiled{
if (!_editTextFiled) {
_editTextFiled = [[MSBaseTextField alloc] init];
NSAttributedString * attribute = [[NSAttributedString alloc] initWithString:YMLocalizedString(@"XPRoomSendTextView0") attributes:@{NSFontAttributeName : [UIFont systemFontOfSize:15], NSForegroundColorAttributeName : [UIColor colorWithWhite:1 alpha:0.5]}];
_editTextFiled.attributedPlaceholder = attribute;
_editTextFiled.borderStyle = UITextBorderStyleNone;
_editTextFiled.textColor = [UIColor whiteColor];
_editTextFiled.font = [UIFont systemFontOfSize:13 weight:UIFontWeightMedium];
[_editTextFiled setContentHuggingPriority:UILayoutPriorityDefaultLow forAxis:UILayoutConstraintAxisHorizontal];
}
return _editTextFiled;
}
- (UIButton *)sendButton{
if (!_sendButton) {
_sendButton = [[UIButton alloc] init];
[_sendButton setTitle:YMLocalizedString(@"XPRoomSendTextView1") forState:UIControlStateNormal];
_sendButton.titleLabel.textColor = [UIColor whiteColor];
_sendButton.titleLabel.font = [UIFont systemFontOfSize:12 weight:UIFontWeightMedium];
[_sendButton setBackgroundImage:[UIImage imageWithColor:[DJDKMIMOMColor disableButtonColor] ]forState:UIControlStateDisabled];
[_sendButton setBackgroundImage:[UIImage gradientColorImageFromColors:@[UIColorFromRGB(0x7E5AFF), UIColorFromRGB(0x52CAD3)] gradientType:GradientTypeLeftToRight imgSize:CGSizeMake(10, 10)] forState:UIControlStateNormal];
_sendButton.enabled = NO;
_sendButton.layer.cornerRadius = 7.5;
_sendButton.layer.masksToBounds = YES;
[_sendButton addTarget:self action:@selector(sendButtonDidClick:) forControlEvents:UIControlEventTouchUpInside];
_sendButton.tag = 101;
}
return _sendButton;
}
- (NSMutableArray *)atNames {
if (!_atNames) {
_atNames = [NSMutableArray array];
}
return _atNames;
}
- (NSMutableArray *)atUids {
if (!_atUids) {
_atUids = [NSMutableArray array];
}
return _atUids;
}
- (UIButton *)headlineBtn{
if(!_headlineBtn){
_headlineBtn = [UIButton new];
[_headlineBtn setBackgroundImage:[UIImage getLanguageImage:@"ms_room_message_send_headline_icon"] forState:UIControlStateNormal];
[_headlineBtn addTarget:self action:@selector(showSendheadlineBtnAction) forControlEvents:UIControlEventTouchUpInside];
_headlineBtn.tag = 100;
}
return _headlineBtn;
}
- (UIView *)bgEditTextFiled{
if(!_bgEditTextFiled){
_bgEditTextFiled = [UIView new];
_bgEditTextFiled.backgroundColor = UIColorFromRGB(0x361661);
_bgEditTextFiled.layer.cornerRadius = 18;
_bgEditTextFiled.layer.masksToBounds = YES;
}
return _bgEditTextFiled;
}
@end