chatCellView.m 72 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886
  1. //
  2. // chatCellView.m
  3. // AIIM
  4. //
  5. // Created by gan on 2025/6/24.
  6. //
  7. #import <Foundation/Foundation.h>
  8. #import "chatCellView.h"
  9. #import "ChatLongPressMenuView.h"
  10. #import "ChatPopoverView.h"
  11. #import "CryptoAES.h"
  12. #import <SDWebImage/UIImageView+WebCache.h>
  13. #import <SDWebImage/SDWebImage.h>
  14. #import <AVFoundation/AVFoundation.h>
  15. #import <AVKit/AVKit.h>
  16. #import "config.h"
  17. #import "FilePreviewer.h"
  18. #import "ChatRecordController.h"
  19. #import "QuoteDetailController.h"
  20. #import "UILabel+YBAttributeTextTapAction.h"
  21. #import <SafariServices/SFSafariViewController.h>
  22. // 定义一些常量
  23. static const CGFloat kTextVerticalMargin = 10.0f; // 内容垂直边距
  24. static const CGFloat kTextHorizontalMargin = 12.0f; //文本水平边距
  25. static const CGFloat kVerticalMargin = 18.0f; // 垂直边距
  26. static const CGFloat kContentMaxWidth = 220.0f; // 内容最大宽度
  27. static const CGFloat kAvatarSize = 36.0f; // 头像大小
  28. static const CGFloat kAvatarMargin = 20.0f; // 头像边距
  29. static const CGFloat kAvatarBatchMargin = 70.0f; // 批量操作头像边距
  30. static const CGFloat kBubbleTopMargin = 20.0f; // 气泡顶部距离
  31. static const CGFloat kBubbleBottomMargin = 40.0f; // 气泡底部距离
  32. static const CGFloat kBubbleArrowWidth = 6.0f; // 气泡箭头宽度
  33. static const CGFloat kMinBubbleHeight = 18.0f; // 气泡最小高度
  34. static const CGFloat kMediaCornerRadius = 4.0f;
  35. @interface chatCellView()
  36. // 基本视图
  37. @property (nonatomic, strong) UIImageView *avatarImageView;
  38. @property (nonatomic, strong) UILabel *nameLabel;
  39. @property (nonatomic, strong) UIImageView *bubbleImageView;
  40. @property (nonatomic, strong) UILabel * timeLabel;
  41. @property (nonatomic, strong) UILabel * readStateLbl;
  42. @property (nonatomic, strong) UIButton * batchStateBtn;
  43. // 发送进度圆环
  44. @property (nonatomic, strong) CAShapeLayer *progressLayer;
  45. @property (nonatomic, strong) CAShapeLayer *progressBackgroundLayer;
  46. @property (nonatomic, strong) UIView *progressContainerView;
  47. // 发送失败按钮
  48. @property (nonatomic, strong) UIButton *resendButton;
  49. // 内容视图
  50. @property (nonatomic, strong) UILabel *textLbl;
  51. @property (nonatomic, strong) UIImageView *imageContentView;
  52. @property (nonatomic, strong) UIView *videoContentView;
  53. @property (nonatomic, strong) UIImageView *thumbnailView;
  54. @property (nonatomic, strong) UIImageView *loadingImg;
  55. @property (nonatomic, strong) UIView *fileContentView;
  56. @property (nonatomic, strong) UIView *voiceContentView;
  57. @property (nonatomic, strong) UIView *callContentView;
  58. @property (nonatomic, strong) UIView *historyContentView;
  59. @property (nonatomic, strong) UILabel * eventLbl;
  60. @property (nonatomic, strong) UILabel * callbackLbl;
  61. @property (nonatomic, strong) UILabel * deleateLbl;
  62. @property (nonatomic, strong) UILabel * quoteLbl;
  63. //@property (nonatomic, strong) UILabel * jinduLbl;
  64. @property (strong, nonatomic) AVPlayer *player;
  65. @property (strong, nonatomic) AVPlayerViewController *playerViewController;
  66. // 当前显示的内容视图
  67. @property (nonatomic, weak) UIView *currentContentView;
  68. @property (nonatomic,strong) NSArray *matchesArray;
  69. @end
  70. @implementation chatCellView
  71. - (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier {
  72. self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
  73. if (self) {
  74. [self initAlllSubviews];
  75. self.selectionStyle = UITableViewCellSelectionStyleNone;
  76. self.backgroundColor = [UIColor clearColor];
  77. }
  78. return self;
  79. }
  80. - (void)layoutSubviews {
  81. [super layoutSubviews];
  82. if (_currentContentView && _messageModel.isSender) {
  83. CGFloat offset = _messageModel.messageType == ChatMessageTypeFile ? 16 : 8;
  84. [_progressContainerView mas_remakeConstraints:^(MASConstraintMaker *make) {
  85. make.width.height.mas_equalTo(30);
  86. make.right.equalTo(_currentContentView.mas_left).offset(-offset);
  87. make.centerY.equalTo(_currentContentView);
  88. }];
  89. [_resendButton mas_remakeConstraints:^(MASConstraintMaker *make) {
  90. make.right.equalTo(_currentContentView.mas_left).offset(-8);
  91. make.centerY.equalTo(_currentContentView);
  92. }];
  93. }
  94. }
  95. -(void)initAlllSubviews{
  96. //复选框
  97. _batchStateBtn = [UIButton buttonWithType:UIButtonTypeCustom];
  98. [_batchStateBtn setBackgroundImage:kImageMake(@"checkbox_unselected") forState:UIControlStateNormal];
  99. [_batchStateBtn setBackgroundImage:kImageMake(@"checkbox_selected") forState:UIControlStateSelected];
  100. _batchStateBtn.hidden = YES;
  101. [self.contentView addSubview:_batchStateBtn];
  102. [_batchStateBtn addTarget:self action:@selector(batchStateButtonClicked) forControlEvents:UIControlEventTouchUpInside];
  103. // 头像
  104. _avatarImageView = [UIImageView new];
  105. _avatarImageView.layer.cornerRadius = kAvatarSize / 2;
  106. _avatarImageView.layer.masksToBounds = YES;
  107. _avatarImageView.userInteractionEnabled = YES;
  108. _avatarImageView.contentMode = UIViewContentModeScaleAspectFill;
  109. [self.contentView addSubview:_avatarImageView];
  110. UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleAvatarTap)];
  111. [_avatarImageView addGestureRecognizer:tap];
  112. // [_avatarImageView jk_addLongPressActionWithBlock:^(UIGestureRecognizer *gestureRecoginzer) {
  113. // [self handleAvatarLongPress];
  114. // }];
  115. // 名字
  116. _nameLabel = [UILabel new];
  117. _nameLabel.font = SYSFONT(12);
  118. _nameLabel.textColor = [UIColor whiteColor];
  119. [self.contentView addSubview:_nameLabel];
  120. // 时间
  121. _timeLabel = [UILabel new];
  122. _timeLabel.font = SYSFONT(12);
  123. _timeLabel.textColor = UIColor.whiteColor;
  124. [self.contentView addSubview:_timeLabel];
  125. _readStateLbl = [UILabel new];
  126. _readStateLbl.font = SYSFONT(12);
  127. _readStateLbl.textColor = UIColor.whiteColor;
  128. [self.contentView addSubview:_readStateLbl];
  129. // 气泡背景
  130. _bubbleImageView = [UIImageView new];
  131. _bubbleImageView.userInteractionEnabled = YES;
  132. [self.contentView addSubview:_bubbleImageView];
  133. // 初始化所有内容视图
  134. [self setupTextContentView];
  135. [self setupImageContentView];
  136. [self setupVideoContentView];
  137. [self setupFileContentView];
  138. [self setupVoiceContentView];
  139. [self setupCallContentView];
  140. [self setupHistoryContentView];
  141. [self setupEventContentView];
  142. [self setupCallbackContentView];
  143. [self setupdeleateContentView];
  144. // 初始化进度圆环
  145. [self setupProgressView];
  146. // 初始化发送失败按钮
  147. [self setupResendButton];
  148. }
  149. #pragma mark - 进度圆环配置
  150. - (void)setupProgressView {
  151. // 容器视图
  152. _progressContainerView = [[UIView alloc] init];
  153. _progressContainerView.hidden = YES;
  154. [self.contentView addSubview:_progressContainerView];
  155. // 圆环尺寸
  156. CGFloat size = 30.0f;
  157. CGFloat lineWidth = 2.0f;
  158. CGRect circleFrame = CGRectMake(0, 0, size, size);
  159. UIBezierPath *circlePath = [UIBezierPath bezierPathWithArcCenter:CGPointMake(size/2, size/2)
  160. radius:(size - lineWidth) / 2
  161. startAngle:-M_PI_2
  162. endAngle:M_PI_2 * 3
  163. clockwise:YES];
  164. // 背景圆环
  165. _progressBackgroundLayer = [CAShapeLayer layer];
  166. _progressBackgroundLayer.path = circlePath.CGPath;
  167. _progressBackgroundLayer.fillColor = [UIColor clearColor].CGColor;
  168. _progressBackgroundLayer.strokeColor = [UIColor colorWithWhite:1.0 alpha:0.3].CGColor;
  169. _progressBackgroundLayer.lineWidth = lineWidth;
  170. _progressBackgroundLayer.frame = circleFrame;
  171. [_progressContainerView.layer addSublayer:_progressBackgroundLayer];
  172. // 进度圆环
  173. _progressLayer = [CAShapeLayer layer];
  174. _progressLayer.path = circlePath.CGPath;
  175. _progressLayer.fillColor = [UIColor clearColor].CGColor;
  176. _progressLayer.strokeColor = [UIColor whiteColor].CGColor;
  177. _progressLayer.lineWidth = lineWidth;
  178. _progressLayer.lineCap = kCALineCapRound;
  179. _progressLayer.strokeEnd = 0.0f;
  180. _progressLayer.frame = circleFrame;
  181. [_progressContainerView.layer addSublayer:_progressLayer];
  182. }
  183. // 更新进度圆环
  184. - (void)updateProgress:(CGFloat)progress {
  185. if (progress < 0) progress = 0;
  186. if (progress > 1) progress = 1;
  187. dispatch_async(dispatch_get_main_queue(), ^{
  188. self.progressLayer.strokeEnd = progress;
  189. // // 如果进度完成,隐藏圆环
  190. // if (progress >= 1.0) {
  191. // self.progressContainerView.hidden = YES;
  192. // }
  193. });
  194. }
  195. // 显示进度圆环
  196. - (void)showProgressView {
  197. dispatch_async(dispatch_get_main_queue(), ^{
  198. self.progressContainerView.hidden = NO;
  199. self.progressLayer.strokeEnd = 0.0f;
  200. });
  201. }
  202. // 隐藏进度圆环
  203. - (void)hideProgressView {
  204. dispatch_async(dispatch_get_main_queue(), ^{
  205. self.progressContainerView.hidden = YES;
  206. });
  207. }
  208. #pragma mark - 发送失败按钮配置
  209. - (void)setupResendButton {
  210. _resendButton = [UIButton buttonWithType:UIButtonTypeCustom];
  211. [_resendButton setImage:[UIImage imageNamed:@"icon_resend"] forState:UIControlStateNormal];
  212. _resendButton.hidden = YES;
  213. [_resendButton addTarget:self action:@selector(handleResendButtonTap) forControlEvents:UIControlEventTouchUpInside];
  214. [self.contentView addSubview:_resendButton];
  215. }
  216. // 显示重发按钮
  217. - (void)showResendButton {
  218. dispatch_async(dispatch_get_main_queue(), ^{
  219. self.resendButton.hidden = NO;
  220. });
  221. }
  222. // 隐藏重发按钮
  223. - (void)hideResendButton {
  224. dispatch_async(dispatch_get_main_queue(), ^{
  225. self.resendButton.hidden = YES;
  226. });
  227. }
  228. // 重发按钮点击事件
  229. - (void)handleResendButtonTap {
  230. NSLog(@"点击重发按钮: msgId=%@", _messageModel.msgId);
  231. // 触发重发回调
  232. if (self.resendMessageBlock) {
  233. self.resendMessageBlock(_messageModel);
  234. }
  235. }
  236. #pragma mark - 内容视图配置
  237. - (void)setupTextContentView {
  238. _textLbl = [UILabel new];
  239. _textLbl.numberOfLines = 0;
  240. _textLbl.textColor = UIColor.blackColor;
  241. _textLbl.userInteractionEnabled = YES; // 允许用户交互
  242. [self.contentView addSubview:_textLbl];
  243. // UITapGestureRecognizer *taptext = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(labelTapped:)];
  244. // [_textLbl addGestureRecognizer:taptext];
  245. _quoteLbl = [UILabel new];
  246. _quoteLbl.numberOfLines = 1;
  247. _quoteLbl.font = SYSFONT(16);
  248. _quoteLbl.textColor = UIColor.whiteColor;
  249. _quoteLbl.layer.cornerRadius = 2.f;
  250. _quoteLbl.layer.masksToBounds = YES;
  251. _quoteLbl.userInteractionEnabled = YES; // 允许用户交互
  252. [self.contentView addSubview:_quoteLbl];
  253. // _quoteLbl.backgroundColor = [UIColor redColor];
  254. // 添加点击手势
  255. UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleQuoteTap)];
  256. [_quoteLbl addGestureRecognizer:tap];
  257. [self.contentView bringSubviewToFront:_quoteLbl];
  258. }
  259. - (void)setupImageContentView {
  260. _imageContentView = [UIImageView new];
  261. _imageContentView.contentMode = UIViewContentModeScaleAspectFit;
  262. _imageContentView.clipsToBounds = YES;
  263. _imageContentView.layer.cornerRadius = kMediaCornerRadius;
  264. _imageContentView.layer.masksToBounds = YES;
  265. _imageContentView.userInteractionEnabled = YES;
  266. [self.contentView addSubview:_imageContentView];
  267. // 添加点击手势
  268. UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleImageTap)];
  269. [_imageContentView addGestureRecognizer:tap];
  270. }
  271. - (void)setupVideoContentView {
  272. _videoContentView = [UIView new];
  273. _videoContentView.layer.cornerRadius = kMediaCornerRadius;
  274. _videoContentView.layer.masksToBounds = YES;
  275. _videoContentView.backgroundColor = [UIColor colorWithWhite:0.95 alpha:1.0];
  276. _videoContentView.userInteractionEnabled = YES;
  277. _thumbnailView = [[UIImageView alloc] init];
  278. _thumbnailView.contentMode = UIViewContentModeScaleAspectFill;
  279. _thumbnailView.clipsToBounds = YES;
  280. _thumbnailView.backgroundColor = [UIColor colorWithWhite:0.95 alpha:1.0];
  281. [_videoContentView addSubview:_thumbnailView];
  282. [_thumbnailView mas_makeConstraints:^(MASConstraintMaker *make) {
  283. make.edges.equalTo(_videoContentView);
  284. }];
  285. NSString *gifPath = [[NSBundle mainBundle] pathForResource:@"load" ofType:@"gif"];
  286. NSData *gifData = [NSData dataWithContentsOfFile:gifPath];
  287. UIImage *placeholder = [UIImage sd_imageWithGIFData:gifData];
  288. _loadingImg = [[UIImageView alloc] initWithImage:placeholder];
  289. [_videoContentView addSubview:_loadingImg];
  290. [_loadingImg mas_makeConstraints:^(MASConstraintMaker *make) {
  291. make.center.equalTo(_videoContentView);
  292. make.width.height.mas_equalTo(100);
  293. }];
  294. _loadingImg.alpha = 0;
  295. UIImageView *playIcon = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"play_btn"]];
  296. [_videoContentView addSubview:playIcon];
  297. [playIcon mas_makeConstraints:^(MASConstraintMaker *make) {
  298. make.center.equalTo(_videoContentView);
  299. make.width.height.mas_equalTo(40);
  300. }];
  301. [self.contentView addSubview:_videoContentView];
  302. // 添加点击手势
  303. UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleVideoTap)];
  304. [_videoContentView addGestureRecognizer:tap];
  305. }
  306. - (void)setupFileContentView {
  307. _fileContentView = [UIView new];
  308. UIImageView *iconView = [[UIImageView alloc] init];
  309. UILabel *nameLabel = [[UILabel alloc] init];
  310. nameLabel.textColor = UIColor.blackColor;
  311. nameLabel.font = [UIFont systemFontOfSize:14];
  312. nameLabel.numberOfLines = 1;
  313. UILabel *sizeLabel = [[UILabel alloc] init];
  314. sizeLabel.font = [UIFont systemFontOfSize:12];
  315. sizeLabel.textColor = [UIColor grayColor];
  316. [_fileContentView addSubview:iconView];
  317. [_fileContentView addSubview:nameLabel];
  318. [_fileContentView addSubview:sizeLabel];
  319. [iconView mas_makeConstraints:^(MASConstraintMaker *make) {
  320. make.left.equalTo(_fileContentView).offset(8);
  321. make.centerY.equalTo(_fileContentView);
  322. make.width.height.mas_equalTo(40);
  323. }];
  324. [nameLabel mas_makeConstraints:^(MASConstraintMaker *make) {
  325. make.left.equalTo(iconView.mas_right).offset(8);
  326. make.top.equalTo(_fileContentView).offset(8);
  327. make.right.equalTo(_fileContentView).offset(-8);
  328. }];
  329. [sizeLabel mas_makeConstraints:^(MASConstraintMaker *make) {
  330. make.left.equalTo(nameLabel);
  331. make.top.equalTo(nameLabel.mas_bottom).offset(4);
  332. // make.right.equalTo(nameLabel);
  333. // make.bottom.lessThanOrEqualTo(_fileContentView).offset(-8);
  334. }];
  335. [self.contentView addSubview:_fileContentView];
  336. // 添加点击手势
  337. UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleFileTap)];
  338. [_fileContentView addGestureRecognizer:tap];
  339. }
  340. - (void)setupVoiceContentView {
  341. _voiceContentView = [UIView new];
  342. UIImageView *voiceIcon = [[UIImageView alloc] initWithImage:kImageMake(@"play_btn")];
  343. UILabel *durationLabel = [[UILabel alloc] init];
  344. durationLabel.textColor = UIColor.blackColor;
  345. durationLabel.font = [UIFont systemFontOfSize:14];
  346. [_voiceContentView addSubview:voiceIcon];
  347. [_voiceContentView addSubview:durationLabel];
  348. [voiceIcon mas_makeConstraints:^(MASConstraintMaker *make) {
  349. make.centerY.equalTo(_voiceContentView);
  350. make.width.height.mas_equalTo(20);
  351. }];
  352. [durationLabel mas_makeConstraints:^(MASConstraintMaker *make) {
  353. make.centerY.equalTo(_voiceContentView);
  354. make.left.equalTo(voiceIcon.mas_right).offset(8);
  355. }];
  356. [self.contentView addSubview:_voiceContentView];
  357. // 添加点击手势
  358. UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleVoiceTap)];
  359. [_voiceContentView addGestureRecognizer:tap];
  360. }
  361. - (void)setupCallContentView {
  362. _callContentView = [UIView new];
  363. UIImageView *callIcon = [[UIImageView alloc] init];
  364. UILabel *callLabel = [[UILabel alloc] init];
  365. callLabel.textColor = UIColor.blackColor;
  366. callLabel.font = [UIFont systemFontOfSize:16];
  367. UILabel *durationLabel = [[UILabel alloc] init];
  368. durationLabel.font = [UIFont systemFontOfSize:16];
  369. durationLabel.textColor = [UIColor grayColor];
  370. [_callContentView addSubview:callIcon];
  371. [_callContentView addSubview:callLabel];
  372. [_callContentView addSubview:durationLabel];
  373. // [callIcon mas_makeConstraints:^(MASConstraintMaker *make) {
  374. // make.left.equalTo(_callContentView).offset(8);
  375. // make.centerY.equalTo(_callContentView);
  376. // make.width.height.mas_equalTo(20);
  377. // }];
  378. //
  379. // [callLabel mas_makeConstraints:^(MASConstraintMaker *make) {
  380. // make.left.equalTo(callIcon.mas_right).offset(8);
  381. // make.top.equalTo(_callContentView).offset(8);
  382. //// make.width.mas_lessThanOrEqualTo(70);
  383. //// make.right.equalTo(_callContentView).offset(-8);
  384. // }];
  385. //
  386. // [durationLabel mas_makeConstraints:^(MASConstraintMaker *make) {
  387. // make.left.equalTo(callLabel.mas_right).offset(8);
  388. // make.top.equalTo(callLabel);
  389. // make.right.equalTo(_callContentView).offset(-8);
  390. // make.bottom.equalTo(_callContentView).offset(-8);
  391. // }];
  392. [self.contentView addSubview:_callContentView];
  393. // 添加点击手势
  394. // UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleCallTap)];
  395. // [_callContentView addGestureRecognizer:tap];
  396. }
  397. - (void)setupHistoryContentView {
  398. _historyContentView = [UIView new];
  399. UILabel *titleLabel = [[UILabel alloc] init];
  400. titleLabel.font = SYSBFONT(14);
  401. titleLabel.text = @"聊天记录";
  402. titleLabel.textColor = UIColor.blackColor;
  403. UILabel *contentLabel = [[UILabel alloc] init];
  404. contentLabel.font = SYSFONT(12);
  405. contentLabel.numberOfLines = 6;
  406. // contentLabel.displaysAsynchronously = YES;
  407. [_historyContentView addSubview:titleLabel];
  408. [_historyContentView addSubview:contentLabel];
  409. [titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
  410. make.left.top.equalTo(_historyContentView).offset(8);
  411. make.right.equalTo(_historyContentView).offset(-8);
  412. make.height.mas_equalTo(14);
  413. }];
  414. [contentLabel mas_makeConstraints:^(MASConstraintMaker *make) {
  415. make.left.right.equalTo(titleLabel);
  416. make.top.equalTo(titleLabel.mas_bottom).offset(4);
  417. make.bottom.equalTo(_historyContentView).offset(-8);
  418. }];
  419. [self.contentView addSubview:_historyContentView];
  420. // 添加点击手势
  421. UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleHistoryTap)];
  422. [_historyContentView addGestureRecognizer:tap];
  423. }
  424. - (void)setupEventContentView {
  425. _eventLbl = [[UILabel alloc] init];
  426. _eventLbl.font = SYSFONT(14);
  427. _eventLbl.textColor = UIColor.whiteColor;
  428. _eventLbl.layer.cornerRadius = 2.f;
  429. _eventLbl.layer.masksToBounds = YES;
  430. [self.contentView addSubview:_eventLbl];
  431. }
  432. - (void)setupCallbackContentView {
  433. _callbackLbl = [[UILabel alloc] init];
  434. _callbackLbl.font = SYSFONT(14);
  435. _callbackLbl.textColor = UIColor.whiteColor;
  436. _callbackLbl.layer.cornerRadius = 2.f;
  437. _callbackLbl.layer.masksToBounds = YES;
  438. [self.contentView addSubview:_callbackLbl];
  439. }
  440. - (void)setupdeleateContentView {
  441. _deleateLbl = [[UILabel alloc] init];
  442. _deleateLbl.font = SYSFONT(14);
  443. _deleateLbl.textColor = UIColor.blackColor;
  444. _deleateLbl.layer.cornerRadius = 2.f;
  445. _deleateLbl.layer.masksToBounds = YES;
  446. [self.contentView addSubview:_deleateLbl];
  447. }
  448. #pragma mark - 数据绑定
  449. - (void)setMessageModel:(ChatMessageModel *)messageModel {
  450. // NSLog(@"messageModel:%@",messageModel);
  451. _messageModel = messageModel;
  452. // 隐藏所有内容视图
  453. _textLbl.hidden = YES;
  454. _quoteLbl.hidden = YES;
  455. _imageContentView.hidden = YES;
  456. _videoContentView.hidden = YES;
  457. _fileContentView.hidden = YES;
  458. _voiceContentView.hidden = YES;
  459. _callContentView.hidden = YES;
  460. _historyContentView.hidden = YES;
  461. _eventLbl.hidden = YES;
  462. _callbackLbl.hidden = YES;
  463. _deleateLbl.hidden = YES;
  464. _readStateLbl.hidden = YES;
  465. // 根据消息类型配置内容
  466. switch (messageModel.messageType) {
  467. case ChatMessageTypeText:
  468. [self setupTextContent];
  469. break;
  470. case ChatMessageTypeImage:
  471. [self setupImageContent];
  472. break;
  473. case ChatMessageTypeVideo:
  474. [self setupVideoContent];
  475. break;
  476. case ChatMessageTypeFile:
  477. [self setupFileContent];
  478. break;
  479. case ChatMessageTypeCallBack:
  480. //撤回
  481. [self setupCallbackContent];
  482. break;
  483. case ChatMessageTypeVoice:
  484. [self setupVoiceContent];
  485. break;
  486. case ChatMessageTypeCall:
  487. [self setupCallContent];
  488. break;
  489. case ChatMessageTypeHistory:
  490. [self setupHistoryContent];
  491. break;
  492. case ChatMessageTypeEvent:
  493. [self setupEventContent];
  494. break;
  495. case ChatMessageTypeCallBack2:
  496. //撤回PC
  497. [self setupCallbackContent];
  498. break;
  499. case ChatMessageTypeDel:
  500. [self setupDeleateContent];
  501. break;
  502. }
  503. // 配置头像和名字
  504. [self setupAvatarAndName];
  505. // 配置气泡背景
  506. [self setupBubbleBackground];
  507. // 更新布局
  508. [self layoutContentViews];
  509. //长按事件
  510. [self setupLongPressEvent];
  511. // 配置发送进度
  512. [self setupSendingProgress];
  513. }
  514. #pragma mark - 批量状态
  515. - (void)setBatchState:(BOOL)batchState{
  516. if (_messageModel.messageType == ChatMessageTypeEvent || _messageModel.messageType == ChatMessageTypeCallBack || _messageModel.messageType == ChatMessageTypeCallBack2) {
  517. self.batchStateBtn.hidden = YES;
  518. return;
  519. }
  520. _batchState = batchState;
  521. self.batchStateBtn.hidden = !batchState;
  522. if (!_messageModel.isSender) {
  523. if (batchState) {
  524. [_avatarImageView mas_remakeConstraints:^(MASConstraintMaker *make) {
  525. make.size.mas_equalTo(CGSizeMake(kAvatarSize, kAvatarSize));
  526. make.left.mas_equalTo(kAvatarBatchMargin);
  527. make.top.equalTo(self.contentView).offset(kVerticalMargin);
  528. }];
  529. }else{
  530. [_avatarImageView mas_remakeConstraints:^(MASConstraintMaker *make) {
  531. make.size.mas_equalTo(CGSizeMake(kAvatarSize, kAvatarSize));
  532. make.left.mas_equalTo(kAvatarMargin);
  533. make.top.equalTo(self.contentView).offset(kVerticalMargin);
  534. }];
  535. }
  536. }
  537. self.batchStateBtn.selected = NO;
  538. }
  539. - (void)setupAvatarAndName {
  540. self.readStateLbl.text = nil;
  541. // 这里应该根据实际数据设置头像和名字
  542. if (_messageModel.avatar) {
  543. [_avatarImageView sd_setImageWithURL:getURL(_messageModel.avatar) placeholderImage:kImageMake(@"Avatar")];
  544. }else{
  545. _avatarImageView.image = kImageMake(@"Avatar");
  546. }
  547. _timeLabel.text = _messageModel.formatterTime;
  548. _readStateLbl.text = _messageModel.readStatus;
  549. if(_messageModel.readstate==4){
  550. _readStateLbl.textColor = globalColor(GCTypeOrangeR);
  551. }
  552. else{
  553. _readStateLbl.textColor = [UIColor whiteColor];
  554. }
  555. if (_messageModel.type==1) {
  556. if (_messageModel.nickName && ![_messageModel.nickName isKindOfClass:NSNull.class]) {
  557. _nameLabel.text = _messageModel.isSender ? @"": _messageModel.nickName;
  558. _nameLabel.textAlignment = _messageModel.isSender ? NSTextAlignmentRight : NSTextAlignmentLeft;
  559. }
  560. }
  561. if (_messageModel.messageType == ChatMessageTypeEvent || _messageModel.messageType == ChatMessageTypeCallBack || _messageModel.messageType == ChatMessageTypeCallBack2) {
  562. _avatarImageView.hidden = YES;
  563. _nameLabel.hidden = YES;
  564. _readStateLbl.hidden = YES;
  565. _timeLabel.hidden = YES;
  566. }else{
  567. _avatarImageView.hidden = NO;
  568. _nameLabel.hidden = NO;
  569. _readStateLbl.hidden = NO;
  570. _timeLabel.hidden = NO;
  571. }
  572. if (_messageModel.type == 0&& _messageModel.isSender) {
  573. _readStateLbl.hidden = NO;
  574. }else{
  575. _readStateLbl.hidden = YES;
  576. }
  577. }
  578. - (void)setupBubbleBackground {
  579. // 图片和视频类型不需要气泡背景
  580. if (_messageModel.messageType == ChatMessageTypeImage || _messageModel.messageType == ChatMessageTypeVideo || _messageModel.messageType == ChatMessageTypeEvent|| _messageModel.messageType == ChatMessageTypeCallBack || _messageModel.messageType == ChatMessageTypeCallBack2) {
  581. _bubbleImageView.hidden = YES;
  582. return;
  583. }
  584. _bubbleImageView.hidden = NO;
  585. UIImage *bubbleImage = _messageModel.isSender ? [UIImage imageNamed:@"rightlt"] : [UIImage imageNamed:@"leftlt"];
  586. // 拉伸气泡图片
  587. UIEdgeInsets insets = UIEdgeInsetsMake(30, _messageModel.isSender ? 20 : 10, 10, _messageModel.isSender ? 10 : 20);
  588. bubbleImage = [bubbleImage resizableImageWithCapInsets:insets resizingMode:UIImageResizingModeStretch];
  589. _bubbleImageView.image = bubbleImage;
  590. }
  591. - (void)setupLongPressEvent{
  592. if (_isHistory) {
  593. return;
  594. }
  595. if ( _messageModel.messageType == ChatMessageTypeEvent || _messageModel.messageType == ChatMessageTypeCallBack || _messageModel.messageType == ChatMessageTypeCall || _messageModel.messageType == ChatMessageTypeCallBack2) {
  596. return;
  597. }
  598. // NSLog(@"setupLongPressEvent-------1");
  599. // 创建长按手势识别器并设置目标方法
  600. UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(longPressEvent:)];
  601. longPress.minimumPressDuration = 0.3; // 设置长按的最小时间为0.3秒
  602. [self.currentContentView addGestureRecognizer:longPress]; // 将手势识别器添加到视图上
  603. if(_messageModel.messageType ==ChatMessageTypeText){
  604. [self.bubbleImageView addGestureRecognizer:longPress]; // 将手势识别器添加到视图上
  605. }
  606. else{
  607. [self.currentContentView addGestureRecognizer:longPress]; // 将手势识别器添加到视图上
  608. }
  609. }
  610. // 配置发送进度
  611. - (void)setupSendingProgress {
  612. // 只有发送方才显示进度或失败按钮
  613. if (!_messageModel.isSender || !_messageModel.isUploadFile) {
  614. [self hideProgressView];
  615. [self hideResendButton];
  616. return;
  617. }
  618. // 根据消息状态显示进度或失败按钮
  619. switch (_messageModel.messageSendStatus) {
  620. case MessageSending: {
  621. // 发送中,显示进度圆环,隐藏失败按钮
  622. [self showProgressView];
  623. [self hideResendButton];
  624. // 如果有上传进度回调,监听进度
  625. weakSelf(self);
  626. if (_messageModel.isUploadFile) {
  627. _messageModel.uploadPersentChange = ^(NSInteger persent, NSInteger localtime) {
  628. if (localtime == weakself.messageModel.localtime) {
  629. CGFloat progress = persent / 100.0f;
  630. [weakself updateProgress:progress];
  631. if (progress >= 1) {
  632. weakself.messageModel.messageSendStatus = MessageSent;
  633. }
  634. }
  635. };
  636. }
  637. break;
  638. }
  639. case MessageSendFail: {
  640. // 发送失败,显示失败按钮,隐藏进度圆环
  641. [self hideProgressView];
  642. [self showResendButton];
  643. break;
  644. }
  645. case MessageSent:
  646. // 其他状态隐藏进度和失败按钮
  647. [self hideProgressView];
  648. [self hideResendButton];
  649. break;
  650. }
  651. }
  652. - (void)longPressEvent:(UILongPressGestureRecognizer *)gestureRecognizer {
  653. if (gestureRecognizer.state == UIGestureRecognizerStateBegan) {
  654. NSLog(@"长按事件开始");
  655. // 在这里添加你的代码,例如显示菜单、编辑选项等
  656. if (_messageModel.messageType == ChatMessageTypeDel || _messageModel.messageType == ChatMessageTypeCallBack) {
  657. return;
  658. }
  659. weakSelf(self);
  660. if(weakself.bubbleCellLongPressMenuBlock){
  661. weakself.bubbleCellLongPressMenuBlock(99);
  662. }
  663. BOOL isSender = NO;
  664. if (_messageModel.isSender) {
  665. isSender = YES;
  666. }
  667. ChatLongPressMenuView * contenView = [[ChatLongPressMenuView alloc] initWithMessageType:_messageModel.messageType isSender:isSender];
  668. BOOL isMedia = NO;
  669. if (_messageModel.messageType == ChatMessageTypeImage || _messageModel.messageType == ChatMessageTypeVideo) {
  670. isMedia = YES;
  671. }else{
  672. isMedia = NO;
  673. }
  674. ChatPopoverView * popover = [[ChatPopoverView alloc] initWithContentView:contenView sourceView:isMedia ? self.currentContentView : self.bubbleImageView];
  675. [popover show];
  676. contenView.indexOfMenuClicked = ^(NSInteger index) {
  677. [popover dismiss];
  678. !weakself.bubbleCellLongPressMenuBlock ?: weakself.bubbleCellLongPressMenuBlock(index);
  679. };
  680. } else if (gestureRecognizer.state == UIGestureRecognizerStateEnded) {
  681. NSLog(@"长按事件结束");
  682. }
  683. NSLog(@"longPressEvent-------");
  684. }
  685. - (void)batchStateButtonClicked{
  686. self.batchStateBtn.selected = !self.batchStateBtn.isSelected;
  687. !self.batchSelectedStateBlock ?: self.batchSelectedStateBlock(self.batchStateBtn.isSelected);
  688. }
  689. #pragma mark - 内容配置具体实现
  690. - (void)setupTextContent {
  691. _textLbl.hidden = NO;
  692. if (_messageModel.quoteMessage) {
  693. self.quoteLbl.hidden = NO;
  694. self.quoteLbl.text = [NSString stringWithFormat:@"%@:%@",_messageModel.quoteMessage.nickName,_messageModel.quoteMessage.content];
  695. }else{
  696. _quoteLbl.hidden = YES;
  697. }
  698. // NSLog(@"_messageModel.content:%@",_messageModel.content);
  699. // 创建富文本
  700. NSMutableAttributedString *text = [[NSMutableAttributedString alloc] initWithString:_messageModel.content ?: @""];
  701. // 处理特殊内容(链接、@用户等)
  702. [self highlightSpecialElementsInText:text];
  703. // 同步设置文本,避免闪烁
  704. // [UIView performWithoutAnimation:^{
  705. // _textLbl.attributedText = text;
  706. // }];
  707. if(_matchesArray.count>0){
  708. NSMutableArray *array = [NSMutableArray new];
  709. for (NSTextCheckingResult *match in _matchesArray) {
  710. if (match.resultType == NSTextCheckingTypeLink) {
  711. NSString *url =[NSString stringWithFormat:@"%@",match.URL];
  712. url=[url stringByReplacingOccurrencesOfString:@"http://" withString:@""];
  713. url=[url stringByReplacingOccurrencesOfString:@"https://" withString:@""];
  714. [array addObject:url];
  715. }
  716. }
  717. _textLbl.attributedText = [self getAttributeWith:array string:_messageModel.content orginFont:18 orginColor:[UIColor darkGrayColor] attributeFont:18 attributeColor:[UIColor blueColor]];
  718. // _textLbl.attributedText = text;
  719. [_textLbl yb_addAttributeTapActionWithStrings:array tapClicked:^(UILabel *label, NSString *string, NSRange range, NSInteger index) {
  720. NSLog(@"%ld:%@",(long)index,self->_matchesArray[index]);
  721. NSTextCheckingResult *match=self->_matchesArray[index];
  722. // [[UIApplication sharedApplication] openURL:match.URL options:@{} completionHandler:nil];
  723. // 点击后的操作
  724. SFSafariViewController *svc = [[SFSafariViewController alloc] initWithURL:match.URL];
  725. [self.parentViewController presentViewController:svc animated:YES completion:nil];
  726. // [FilePreviewer.shared previewFileWithLocalPath:@"" remoteURL:match.URL fromViewController:self.parentViewController];
  727. }];
  728. }
  729. else{
  730. _textLbl.attributedText = text;
  731. }
  732. UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(longPressEvent:)];
  733. longPress.minimumPressDuration = 0.3; // 设置长按的最小时间为0.3秒
  734. [_textLbl addGestureRecognizer:longPress]; // 将手势识别器添加到视图上
  735. _currentContentView = _textLbl;
  736. }
  737. - (NSAttributedString *)getAttributeWith:(id)sender
  738. string:(NSString *)string
  739. orginFont:(CGFloat)orginFont
  740. orginColor:(UIColor *)orginColor
  741. attributeFont:(CGFloat)attributeFont
  742. attributeColor:(UIColor *)attributeColor
  743. {
  744. __block NSMutableAttributedString *totalStr = [[NSMutableAttributedString alloc] initWithString:string];
  745. [totalStr addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:orginFont] range:NSMakeRange(0, string.length)];
  746. [totalStr addAttribute:NSForegroundColorAttributeName value:orginColor range:NSMakeRange(0, string.length)];
  747. NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
  748. [paragraphStyle setLineSpacing:0.0f]; //设置行间距
  749. [paragraphStyle setLineBreakMode:NSLineBreakByTruncatingTail];
  750. [paragraphStyle setAlignment:NSTextAlignmentLeft];
  751. [paragraphStyle setLineBreakMode:NSLineBreakByCharWrapping];
  752. [totalStr addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, [totalStr length])];
  753. if ([sender isKindOfClass:[NSArray class]]) {
  754. __block NSString *oringinStr = string;
  755. __weak typeof(self) weakSelf = self;
  756. [sender enumerateObjectsUsingBlock:^(NSString * _Nonnull str, NSUInteger idx, BOOL * _Nonnull stop) {
  757. NSRange range = [oringinStr rangeOfString:str];
  758. if(range.length>0){
  759. [totalStr addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:attributeFont] range:range];
  760. [totalStr addAttribute:NSForegroundColorAttributeName value:attributeColor range:range];
  761. // oringinStr = [oringinStr stringByReplacingCharactersInRange:range withString:[weakSelf getStringWithRange:range]];
  762. }
  763. }];
  764. }else if ([sender isKindOfClass:[NSString class]]) {
  765. NSRange range = [string rangeOfString:sender];
  766. [totalStr addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:attributeFont] range:range];
  767. [totalStr addAttribute:NSForegroundColorAttributeName value:attributeColor range:range];
  768. }
  769. return totalStr;
  770. }
  771. - (NSString *)getStringWithRange:(NSRange)range
  772. {
  773. NSMutableString *string = [NSMutableString string];
  774. for (int i = 0; i < range.length ; i++) {
  775. [string appendString:@" "];
  776. }
  777. return string;
  778. }
  779. #pragma mark - 辅助方法
  780. - (void)highlightSpecialElementsInText:(NSMutableAttributedString *)text {
  781. // 高亮链接
  782. NSDataDetector *detector = [NSDataDetector dataDetectorWithTypes:NSTextCheckingTypeLink error:nil];
  783. NSArray *matches = [detector matchesInString:text.string options:0 range:NSMakeRange(0, text.length)];
  784. NSLog(@"matches:%@",matches);
  785. _matchesArray =matches;
  786. // 高亮@用户(暂不开放)
  787. // NSRegularExpression *atRegex = [NSRegularExpression regularExpressionWithPattern:@"@[\\u4e00-\\u9fa5a-zA-Z0-9_-]+" options:0 error:nil];
  788. // NSArray *atMatches = [atRegex matchesInString:text.string options:0 range:text.yy_rangeOfAll];
  789. //
  790. // for (NSTextCheckingResult *match in atMatches) {
  791. // [text yy_setColor:[UIColor orangeColor] range:match.range];
  792. // [text yy_setTextHighlightRange:match.range
  793. // color:[UIColor orangeColor]
  794. // backgroundColor:[UIColor colorWithWhite:0.9 alpha:0.5]
  795. // tapAction:^(UIView *containerView, NSAttributedString *text, NSRange range, CGRect rect) {
  796. // NSString *atUser = [text.string substringWithRange:range];
  797. // // 处理@用户点击
  798. // NSLog(@"点击了: %@", atUser);
  799. // }];
  800. // }
  801. }
  802. - (void)setupImageContent {
  803. _imageContentView.hidden = NO;
  804. if (_messageModel.localurl && _messageModel.localurl.length != 0) {//显示本地图片
  805. NSURL *localFileURL = getURL(_messageModel.localurl);
  806. // NSLog(@"UIImage------------1");
  807. // 从 URL 获取文件路径
  808. NSString *filePath = localFileURL.path;
  809. // 通过文件路径加载图片
  810. UIImage *image = [UIImage imageWithContentsOfFile:filePath];
  811. if (image) {//本地图片显示成功
  812. // NSLog(@"UIImage------------2");
  813. _imageContentView.image = image;
  814. CGImageRef cgImage = image.CGImage;
  815. CGFloat imageWidth = CGImageGetWidth(cgImage);
  816. CGFloat imageHeight = CGImageGetHeight(cgImage);
  817. CGFloat imageScale = imageWidth/imageHeight;
  818. CGFloat realWidth = 150 * imageScale;
  819. if(realWidth>220){
  820. realWidth=220;
  821. imageHeight=150;
  822. }
  823. else{
  824. imageHeight=150;
  825. }
  826. self.messageModel.mediaSize = CGSizeMake(realWidth, imageHeight);
  827. [self.imageContentView mas_updateConstraints:^(MASConstraintMaker *make) {
  828. make.width.mas_equalTo(realWidth);
  829. }];
  830. _currentContentView = _imageContentView;
  831. return;
  832. }
  833. }
  834. //没有有效本地图片 使用SDWebImage加载图片
  835. weakSelf(self);
  836. [_imageContentView sd_setImageWithURL:[NSURL URLWithString:_messageModel.url]
  837. placeholderImage:[UIImage imageNamed:@"pictrue_placeholder"]
  838. completed:^(UIImage * _Nullable image, NSError * _Nullable error, SDImageCacheType cacheType, NSURL * _Nullable imageURL) {
  839. if (!error && image) {
  840. // 图片加载成功后可以更新布局(如果需要)
  841. // NSLog(@"UIImage------------5");
  842. CGImageRef cgImage = image.CGImage;
  843. CGFloat imageWidth = CGImageGetWidth(cgImage);
  844. CGFloat imageHeight = CGImageGetHeight(cgImage);
  845. CGFloat imageScale = imageWidth/imageHeight;
  846. CGFloat realWidth = 150 * imageScale;
  847. if(realWidth>220){
  848. realWidth=220;
  849. imageHeight=150;
  850. }
  851. else{
  852. imageHeight=150;
  853. }
  854. weakself.messageModel.mediaSize = CGSizeMake(realWidth, 150);
  855. [weakself.imageContentView mas_updateConstraints:^(MASConstraintMaker *make) {
  856. make.width.mas_equalTo(realWidth);
  857. }];
  858. }
  859. }];
  860. _currentContentView = _imageContentView;
  861. }
  862. - (void)setupVideoContent {
  863. _videoContentView.hidden = NO;
  864. // if (_thumbnailView.image) {
  865. // return;
  866. // }
  867. // 清除旧视图
  868. _thumbnailView.image = nil;
  869. _loadingImg.image = nil;
  870. weakSelf(self);
  871. if (_messageModel.videoThumbnailImage) {
  872. // NSLog(@"videoThumbnailImage----:%@",_messageModel.videoThumbnailImage);
  873. _thumbnailView.image = _messageModel.videoThumbnailImage;
  874. [_thumbnailView mas_makeConstraints:^(MASConstraintMaker *make) {
  875. make.edges.equalTo(_videoContentView);
  876. }];
  877. }else{
  878. // NSLog(@"videoThumbnailImage----load");
  879. [_messageModel generateThumbnailWithCompletion:^(UIImage * _Nonnull thumbnail) {
  880. // NSLog(@"111111---------------");
  881. if (thumbnail) {
  882. // NSLog(@"2222---------------");
  883. dispatch_async(dispatch_get_main_queue(), ^{
  884. [weakself.thumbnailView mas_makeConstraints:^(MASConstraintMaker *make) {
  885. make.edges.equalTo(self->_videoContentView);
  886. }];
  887. weakself.thumbnailView.image = thumbnail;
  888. });
  889. }
  890. }];
  891. }
  892. _currentContentView = _videoContentView;
  893. }
  894. - (void)setupFileContent {
  895. _fileContentView.hidden = NO;
  896. // 获取子视图
  897. UIImageView *iconView = _fileContentView.subviews[0];
  898. UILabel *nameLabel = _fileContentView.subviews[1];
  899. UILabel *sizeLabel = _fileContentView.subviews[2];
  900. // 设置文件内容
  901. iconView.image = [UIImage imageNamed: @"file_icon_black"];
  902. nameLabel.text = _messageModel.fileName ?: @"未知文件";
  903. sizeLabel.text = _messageModel.customFileSize ?: @"0KB";
  904. _currentContentView = _fileContentView;
  905. }
  906. - (void)setupVoiceContent {
  907. _voiceContentView.hidden = NO;
  908. // 获取子视图
  909. UIImageView *voiceIcon = _voiceContentView.subviews[0];
  910. UILabel *durationLabel = _voiceContentView.subviews[1];
  911. voiceIcon.animationDuration = 1.f;
  912. voiceIcon.animationRepeatCount = 0;
  913. // 设置语音内容
  914. voiceIcon.image = [UIImage imageNamed:_messageModel.isSender ? @"yuyinR" : @"yuyinL"];
  915. durationLabel.text = [NSString stringWithFormat:@"%ld\"", (long)_messageModel.voiceDuration];
  916. // 根据发送方调整布局
  917. if (_messageModel.isSender) {
  918. [voiceIcon mas_remakeConstraints:^(MASConstraintMaker *make) {
  919. make.right.equalTo(_voiceContentView).offset(-8);
  920. make.centerY.equalTo(_voiceContentView);
  921. make.width.height.mas_equalTo(20);
  922. }];
  923. [durationLabel mas_remakeConstraints:^(MASConstraintMaker *make) {
  924. make.right.equalTo(voiceIcon.mas_left).offset(-8);
  925. make.centerY.equalTo(_voiceContentView);
  926. }];
  927. voiceIcon.animationImages = @[kImageMake(@"audio_sender_animate1"),kImageMake(@"audio_sender_animate2"),kImageMake(@"audio_sender_animate3")];
  928. } else {
  929. [voiceIcon mas_remakeConstraints:^(MASConstraintMaker *make) {
  930. make.left.equalTo(_voiceContentView).offset(8);
  931. make.centerY.equalTo(_voiceContentView);
  932. make.width.height.mas_equalTo(20);
  933. }];
  934. [durationLabel mas_remakeConstraints:^(MASConstraintMaker *make) {
  935. make.left.equalTo(voiceIcon.mas_right).offset(8);
  936. make.centerY.equalTo(_voiceContentView);
  937. }];
  938. voiceIcon.animationImages = @[kImageMake(@"audio_receiver_animate1"),kImageMake(@"audio_receiver_animate2"),kImageMake(@"audio_receiver_animate3")];
  939. }
  940. _currentContentView = _voiceContentView;
  941. }
  942. - (void)setupCallContent {
  943. _callContentView.hidden = NO;
  944. // 获取子视图
  945. UIImageView *callIcon = _callContentView.subviews[0];
  946. UILabel *callLabel = _callContentView.subviews[1];
  947. UILabel *durationLabel = _callContentView.subviews[2];
  948. // 设置通话记录内容
  949. callIcon.image = [UIImage imageNamed:_messageModel.isVideo ? @"vedio_call_icon" : @"audio_call_icon"];
  950. callLabel.text = _messageModel.isCallSuccess ? @"通话时长" : @"未接通";
  951. durationLabel.text = _messageModel.isCallSuccess ? [self formatTimeWithMilliseconds:_messageModel.callDuration] : @"";
  952. _currentContentView = _callContentView;
  953. }
  954. - (void)setupHistoryContent {
  955. _historyContentView.hidden = NO;
  956. // 获取子视图
  957. UILabel *titleLabel = _historyContentView.subviews[0];
  958. UILabel *contentLabel = (UILabel *)_historyContentView.subviews[1];
  959. // 设置聊天记录内容
  960. titleLabel.text = @"聊天记录";
  961. NSArray * msgArray = _messageModel.forwardMsgArray;
  962. NSMutableArray * contentArray = [NSMutableArray array];
  963. for (NSDictionary * dict in msgArray) {
  964. NSString * messageType = dict[@"messageType"];
  965. NSString * nickName = dict[@"fromName"]?:@"";
  966. NSString * recordString = @"";
  967. switch ([messageType integerValue]) {
  968. case 0:
  969. // recordString = [NSString stringWithFormat:@"%@:%@\n",nickName,dict[@"content"]?:@""];
  970. recordString = [NSString stringWithFormat:@"%@:%@\n",nickName,[CryptoAES.shareInstance decryptDataL:dict[@"content"]]];
  971. break;
  972. case 1:
  973. recordString = [NSString stringWithFormat:@"%@:【图片】\n",nickName];;
  974. break;
  975. case 2:
  976. recordString = [NSString stringWithFormat:@"%@:【文件】\n",nickName];
  977. break;
  978. case 3:
  979. recordString = [NSString stringWithFormat:@"%@:【语音】\n",nickName];
  980. break;
  981. case 5:
  982. recordString = [NSString stringWithFormat:@"%@:【视频】\n",nickName];
  983. break;
  984. case 6:
  985. recordString = [NSString stringWithFormat:@"%@:【转发】\n",nickName];
  986. break;
  987. case 7:
  988. recordString = [NSString stringWithFormat:@"%@:【通话】\n",nickName];
  989. break;
  990. default:
  991. break;
  992. }
  993. [contentArray addObject:recordString];
  994. if (msgArray.lastObject == dict) {
  995. NSString * contentString = [contentArray componentsJoinedByString:@""];
  996. NSMutableAttributedString *content = [[NSMutableAttributedString alloc] initWithString:contentString ?: @""];
  997. contentLabel.attributedText = content;
  998. }
  999. }
  1000. _currentContentView = _historyContentView;
  1001. }
  1002. - (void)setupEventContent {
  1003. _eventLbl.hidden = NO;
  1004. _eventLbl.text = _messageModel.content;
  1005. [_eventLbl mas_remakeConstraints:^(MASConstraintMaker *make) {
  1006. make.height.mas_equalTo(24);
  1007. make.centerX.mas_equalTo(self.contentView.mas_centerX);
  1008. make.centerY.mas_equalTo(self.contentView.mas_centerY);
  1009. }];
  1010. [_eventLbl sizeToFit];
  1011. _currentContentView = _eventLbl;
  1012. }
  1013. - (void)setupCallbackContent {
  1014. _callbackLbl.hidden = NO;
  1015. _callbackLbl.text = _messageModel.isSender ? @"你撤回了一条消息":[NSString stringWithFormat:@"%@撤回了一条消息",_messageModel.nickName];
  1016. [_callbackLbl mas_remakeConstraints:^(MASConstraintMaker *make) {
  1017. make.height.mas_equalTo(24);
  1018. make.centerX.mas_equalTo(self.contentView.mas_centerX);
  1019. make.centerY.mas_equalTo(self.contentView.mas_centerY);
  1020. }];
  1021. _currentContentView = _callbackLbl;
  1022. }
  1023. - (void)setupDeleateContent {
  1024. _deleateLbl.hidden = NO;
  1025. _deleateLbl.text = @"你删除了一条消息!";
  1026. [_deleateLbl mas_remakeConstraints:^(MASConstraintMaker *make) {
  1027. make.height.mas_equalTo(24);
  1028. make.centerX.mas_equalTo(self.contentView.mas_centerX);
  1029. make.centerY.mas_equalTo(self.contentView.mas_centerY);
  1030. }];
  1031. _currentContentView = _deleateLbl;
  1032. }
  1033. #pragma mark - 布局方法
  1034. - (void)layoutContentViews {
  1035. if (_messageModel.messageType == ChatMessageTypeEvent || _messageModel.messageType == ChatMessageTypeCallBack || _messageModel.messageType == ChatMessageTypeCallBack2) {
  1036. return;
  1037. }
  1038. //复选框布局
  1039. // self.batchStateBtn.frame=CGRectMake(20, 10, 32, 32);
  1040. [self.batchStateBtn mas_remakeConstraints:^(MASConstraintMaker *make) {
  1041. make.size.mas_equalTo(CGSizeMake(32, 32));
  1042. make.left.mas_equalTo(20);
  1043. make.top.mas_equalTo(10);
  1044. }];
  1045. // 头像布局
  1046. if (_messageModel.isSender) {
  1047. [_avatarImageView mas_remakeConstraints:^(MASConstraintMaker *make) {
  1048. make.right.equalTo(self.contentView).offset(-kAvatarMargin);
  1049. make.top.equalTo(self.contentView).offset(kVerticalMargin);
  1050. make.width.height.mas_equalTo(kAvatarSize);
  1051. }];
  1052. [_nameLabel mas_remakeConstraints:^(MASConstraintMaker *make) {
  1053. make.right.equalTo(_avatarImageView.mas_left).offset(-4);
  1054. make.top.equalTo(_avatarImageView);
  1055. make.left.greaterThanOrEqualTo(self.contentView).offset(10);
  1056. }];
  1057. [_timeLabel mas_remakeConstraints:^(MASConstraintMaker *make) {
  1058. make.height.mas_equalTo(14);
  1059. make.right.mas_equalTo(self.nameLabel.mas_left).offset(-12);
  1060. make.top.mas_equalTo(self.avatarImageView);
  1061. }];
  1062. if (_currentContentView) {
  1063. [_readStateLbl mas_remakeConstraints:^(MASConstraintMaker *make) {
  1064. make.left.mas_equalTo(_currentContentView.mas_right).offset(6);
  1065. make.height.mas_equalTo(14);
  1066. make.bottom.mas_equalTo(_currentContentView.mas_bottom);
  1067. }];
  1068. }
  1069. } else {
  1070. [_avatarImageView mas_remakeConstraints:^(MASConstraintMaker *make) {
  1071. make.left.equalTo(self.contentView).offset(kAvatarMargin);
  1072. make.top.equalTo(self.contentView).offset(kVerticalMargin);
  1073. make.width.height.mas_equalTo(kAvatarSize);
  1074. }];
  1075. [_nameLabel mas_remakeConstraints:^(MASConstraintMaker *make) {
  1076. make.left.equalTo(_avatarImageView.mas_right).offset(4);
  1077. make.top.equalTo(_avatarImageView);
  1078. make.right.lessThanOrEqualTo(self.contentView).offset(-10);
  1079. }];
  1080. [_timeLabel mas_remakeConstraints:^(MASConstraintMaker *make) {
  1081. make.height.mas_equalTo(14);
  1082. make.left.mas_equalTo(self.nameLabel.mas_right).offset(12);
  1083. make.top.mas_equalTo(self.avatarImageView);
  1084. }];
  1085. }
  1086. // 内容视图布局
  1087. [self layoutCurrentContentView];
  1088. // 气泡背景布局
  1089. if (!_bubbleImageView.hidden) {
  1090. NSAssert(_currentContentView, @"currentContentView 不能为 nil");
  1091. NSAssert(_currentContentView.superview, @"currentContentView 必须已添加到父视图");
  1092. [_bubbleImageView mas_remakeConstraints:^(MASConstraintMaker *make) {
  1093. make.edges.equalTo(_currentContentView).insets(UIEdgeInsetsMake(-kTextVerticalMargin, -kTextHorizontalMargin, -kTextVerticalMargin, -kTextHorizontalMargin));
  1094. }];
  1095. [self.contentView sendSubviewToBack:_bubbleImageView];
  1096. }
  1097. }
  1098. - (void)layoutCurrentContentView {
  1099. switch (_messageModel.messageType) {
  1100. case ChatMessageTypeText:
  1101. [self layoutTextContent];
  1102. break;
  1103. case ChatMessageTypeImage:
  1104. [self layoutImageContent];
  1105. break;
  1106. case ChatMessageTypeVideo:
  1107. [self layoutVideoContent];
  1108. break;
  1109. case ChatMessageTypeVoice:
  1110. [self layoutVioceContent];
  1111. break;
  1112. case ChatMessageTypeCall:
  1113. [self layoutCallContent];
  1114. break;
  1115. case ChatMessageTypeHistory:
  1116. [self layoutHistoryContent];
  1117. break;
  1118. default:
  1119. [self layoutOtherContent];
  1120. break;
  1121. }
  1122. }
  1123. - (void)layoutTextContent {
  1124. CGSize textSize = [self calculateTextSize];
  1125. if (_messageModel.isSender) {
  1126. [_textLbl mas_remakeConstraints:^(MASConstraintMaker *make) {
  1127. make.right.equalTo(_avatarImageView.mas_left).offset(-26);
  1128. make.top.mas_equalTo(_avatarImageView.mas_top).offset(28);
  1129. make.width.mas_equalTo(textSize.width);
  1130. make.height.mas_equalTo(textSize.height);
  1131. make.bottom.equalTo(self.contentView).offset(-kVerticalMargin).priorityHigh();
  1132. }];
  1133. if (_messageModel.quoteMessage) {
  1134. [_quoteLbl mas_remakeConstraints:^(MASConstraintMaker *make) {
  1135. make.height.mas_equalTo(20);
  1136. make.top.mas_equalTo(_textLbl.mas_bottom).offset(20);
  1137. make.right.mas_equalTo(_textLbl.mas_right).offset(6);
  1138. make.width.mas_lessThanOrEqualTo(kContentMaxWidth);
  1139. }];
  1140. }
  1141. } else {
  1142. [_textLbl mas_remakeConstraints:^(MASConstraintMaker *make) {
  1143. make.left.equalTo(_avatarImageView.mas_right).offset(26);
  1144. make.top.mas_equalTo(_avatarImageView.mas_top).offset(28);
  1145. make.width.mas_equalTo(textSize.width);
  1146. make.height.mas_equalTo(textSize.height);
  1147. make.bottom.equalTo(self.contentView).offset(-kVerticalMargin).priorityHigh();
  1148. }];
  1149. if (_messageModel.quoteMessage) {
  1150. [_quoteLbl mas_remakeConstraints:^(MASConstraintMaker *make) {
  1151. make.height.mas_equalTo(20);
  1152. make.top.mas_equalTo(_textLbl.mas_bottom).offset(20);
  1153. make.left.mas_equalTo(_textLbl.mas_left).offset(-6);
  1154. make.width.mas_lessThanOrEqualTo(kContentMaxWidth);
  1155. }];
  1156. }
  1157. }
  1158. }
  1159. - (void)layoutImageContent {
  1160. // CGSize imageSize = [self adjustMediaSize:_messageModel.mediaSize];
  1161. CGSize imageSize = _messageModel.mediaSize;
  1162. if (_messageModel.isSender) {
  1163. [_imageContentView mas_remakeConstraints:^(MASConstraintMaker *make) {
  1164. make.right.equalTo(_avatarImageView.mas_left).offset(-16);
  1165. make.top.mas_equalTo(_avatarImageView.mas_top).offset(28);
  1166. make.width.mas_equalTo(imageSize.width);
  1167. make.height.mas_equalTo(imageSize.height);
  1168. make.bottom.equalTo(self.contentView).offset(-kVerticalMargin).priorityHigh();
  1169. }];
  1170. } else {
  1171. [_imageContentView mas_remakeConstraints:^(MASConstraintMaker *make) {
  1172. make.left.equalTo(_avatarImageView.mas_right).offset(16);
  1173. make.top.mas_equalTo(_avatarImageView.mas_top).offset(28);
  1174. make.width.mas_equalTo(imageSize.width);
  1175. make.height.mas_equalTo(imageSize.height);
  1176. make.bottom.equalTo(self.contentView).offset(-kVerticalMargin).priorityHigh();
  1177. }];
  1178. }
  1179. }
  1180. - (void)layoutVideoContent {
  1181. CGSize videoSize = [self adjustMediaSize:_messageModel.mediaSize];
  1182. if (_messageModel.isSender) {
  1183. [_videoContentView mas_remakeConstraints:^(MASConstraintMaker *make) {
  1184. make.right.equalTo(_avatarImageView.mas_left).offset(-16);
  1185. make.top.mas_equalTo(_avatarImageView.mas_top).offset(28);
  1186. make.width.mas_equalTo(videoSize.width);
  1187. make.height.mas_equalTo(videoSize.height);
  1188. make.bottom.equalTo(self.contentView).offset(-kVerticalMargin).priorityHigh();
  1189. }];
  1190. } else {
  1191. [_videoContentView mas_remakeConstraints:^(MASConstraintMaker *make) {
  1192. make.left.equalTo(_avatarImageView.mas_right).offset(16);
  1193. make.top.mas_equalTo(_avatarImageView.mas_top).offset(28);
  1194. make.width.mas_equalTo(videoSize.width);
  1195. make.height.mas_equalTo(videoSize.height);
  1196. make.bottom.equalTo(self.contentView).offset(-kVerticalMargin).priorityHigh();
  1197. }];
  1198. }
  1199. }
  1200. - (void)layoutVioceContent {
  1201. // 设置内容视图约束
  1202. [_voiceContentView mas_remakeConstraints:^(MASConstraintMaker *make) {
  1203. if (_messageModel.isSender) {
  1204. make.right.equalTo(_avatarImageView.mas_left).offset(-26);
  1205. } else {
  1206. make.left.equalTo(_avatarImageView.mas_right).offset(26);
  1207. }
  1208. make.top.equalTo(_avatarImageView).offset(28);
  1209. make.width.mas_equalTo(_messageModel.voiceWidth);
  1210. make.bottom.equalTo(self.contentView).offset(-kVerticalMargin).priorityHigh();
  1211. }];
  1212. }
  1213. - (void)layoutCallContent {
  1214. // 获取子视图
  1215. UIImageView *callIcon = _callContentView.subviews[0];
  1216. UILabel *callLabel = _callContentView.subviews[1];
  1217. UILabel *durationLabel = _callContentView.subviews[2];
  1218. if (_messageModel.isSender) {
  1219. [_callContentView mas_remakeConstraints:^(MASConstraintMaker *make) {
  1220. make.right.equalTo(_avatarImageView.mas_left).offset(-26);
  1221. make.top.mas_equalTo(_avatarImageView.mas_top).offset(28);
  1222. make.width.mas_lessThanOrEqualTo(kContentMaxWidth);
  1223. make.bottom.equalTo(self.contentView).offset(-kVerticalMargin).priorityHigh();
  1224. }];
  1225. } else {
  1226. [_callContentView mas_remakeConstraints:^(MASConstraintMaker *make) {
  1227. make.left.equalTo(_avatarImageView.mas_right).offset(26);
  1228. make.top.mas_equalTo(_avatarImageView.mas_top).offset(28);
  1229. make.width.mas_lessThanOrEqualTo(kContentMaxWidth);
  1230. make.bottom.equalTo(self.contentView).offset(-kVerticalMargin).priorityHigh();
  1231. }];
  1232. }
  1233. if (_messageModel.isCallSuccess) {
  1234. [callLabel mas_remakeConstraints:^(MASConstraintMaker *make) {
  1235. make.left.equalTo(callIcon.mas_right).offset(8);
  1236. make.top.equalTo(_callContentView).offset(8);
  1237. }];
  1238. [durationLabel mas_remakeConstraints:^(MASConstraintMaker *make) {
  1239. make.left.equalTo(callLabel.mas_right).offset(8);
  1240. make.top.equalTo(callLabel);
  1241. make.right.equalTo(_callContentView).offset(-8);
  1242. make.bottom.equalTo(_callContentView).offset(-8);
  1243. }];
  1244. }else{
  1245. [callLabel mas_remakeConstraints:^(MASConstraintMaker *make) {
  1246. make.left.equalTo(callIcon.mas_right).offset(8);
  1247. make.top.equalTo(_callContentView).offset(8);
  1248. make.width.mas_lessThanOrEqualTo(50);
  1249. make.right.equalTo(_callContentView).offset(-8);
  1250. }];
  1251. }
  1252. }
  1253. - (void)layoutHistoryContent {
  1254. [_historyContentView mas_remakeConstraints:^(MASConstraintMaker *make) {
  1255. if (_messageModel.isSender) {
  1256. make.right.equalTo(_avatarImageView.mas_left).offset(-26);
  1257. } else {
  1258. make.left.equalTo(_avatarImageView.mas_right).offset(26);
  1259. }
  1260. make.top.equalTo(_avatarImageView).offset(28);
  1261. make.width.mas_equalTo(160);
  1262. make.bottom.equalTo(self.contentView).offset(-kVerticalMargin).priorityHigh();
  1263. }];
  1264. }
  1265. - (void)layoutOtherContent {
  1266. if (_messageModel.isSender) {
  1267. [_currentContentView mas_remakeConstraints:^(MASConstraintMaker *make) {
  1268. make.right.equalTo(_avatarImageView.mas_left).offset(-26);
  1269. make.top.mas_equalTo(_avatarImageView.mas_top).offset(28);
  1270. make.width.mas_lessThanOrEqualTo(kContentMaxWidth);
  1271. make.bottom.equalTo(self.contentView).offset(-kVerticalMargin).priorityHigh();
  1272. }];
  1273. } else {
  1274. [_currentContentView mas_remakeConstraints:^(MASConstraintMaker *make) {
  1275. make.left.equalTo(_avatarImageView.mas_right).offset(26);
  1276. make.top.mas_equalTo(_avatarImageView.mas_top).offset(28);
  1277. make.width.mas_lessThanOrEqualTo(kContentMaxWidth);
  1278. make.bottom.equalTo(self.contentView).offset(-kVerticalMargin).priorityHigh();
  1279. }];
  1280. }
  1281. }
  1282. - (CGSize)adjustMediaSize:(CGSize)originalSize {
  1283. CGFloat maxWidth = kContentMaxWidth;
  1284. CGFloat maxHeight = 200.0f;
  1285. if (originalSize.width <= 0 || originalSize.height <= 0) {
  1286. return CGSizeMake(maxWidth, maxWidth * 0.6);
  1287. }
  1288. CGFloat ratio = originalSize.width / originalSize.height;
  1289. CGFloat adjustedWidth = maxWidth;
  1290. CGFloat adjustedHeight = adjustedWidth / ratio;
  1291. if (adjustedHeight > maxHeight) {
  1292. adjustedHeight = maxHeight;
  1293. adjustedWidth = adjustedHeight * ratio;
  1294. }
  1295. return CGSizeMake(adjustedWidth, adjustedHeight);
  1296. }
  1297. + (CGSize)otherAdjustMediaSize:(CGSize)originalSize {
  1298. CGFloat maxWidth = kContentMaxWidth;
  1299. CGFloat maxHeight = 200.0f;
  1300. if (originalSize.width <= 0 || originalSize.height <= 0) {
  1301. return CGSizeMake(maxWidth, maxWidth * 0.6);
  1302. }
  1303. CGFloat ratio = originalSize.width / originalSize.height;
  1304. CGFloat adjustedWidth = maxWidth;
  1305. CGFloat adjustedHeight = adjustedWidth / ratio;
  1306. if (adjustedHeight > maxHeight) {
  1307. adjustedHeight = maxHeight;
  1308. adjustedWidth = adjustedHeight * ratio;
  1309. }
  1310. return CGSizeMake(adjustedWidth, adjustedHeight);
  1311. }
  1312. - (CGSize)calculateTextSize{
  1313. NSString *text = _messageModel.content ?: @"";
  1314. UILabel *label = [[UILabel alloc] init];
  1315. label.font = [UIFont systemFontOfSize:18.0]; // 设置字体大小
  1316. label.numberOfLines = 0; // 设置为0表示不限制行数
  1317. label.text = text; // 设置文本内容
  1318. label.preferredMaxLayoutWidth = kContentMaxWidth; // 设置固定宽度
  1319. CGSize size = [label sizeThatFits:CGSizeMake(kContentMaxWidth, CGFLOAT_MAX)];
  1320. CGSize textSize = size;
  1321. // NSLog(@"文本宽度: %f, 文本高度: %f", textSize.width, textSize.height);
  1322. return textSize;
  1323. }
  1324. - (NSString *)formatTimeWithMilliseconds:(NSInteger)milliseconds{
  1325. NSInteger seconds = milliseconds / 1000.0;
  1326. if (seconds >= 60) {
  1327. // 大于等于60秒时显示为分钟,保留一位小数
  1328. NSInteger minutes = seconds / 60.0;
  1329. NSInteger sc = seconds%60;
  1330. return [NSString stringWithFormat:@"%ld分%ld秒", (long)minutes,(long)sc];
  1331. } else {
  1332. // 小于60秒时显示为秒,保留整数
  1333. return [NSString stringWithFormat:@"%ld秒", seconds];
  1334. }
  1335. }
  1336. #pragma mark 列表事件处理
  1337. - (void)handleImageTap {
  1338. if (_messageModel.messageType == ChatMessageTypeImage) {
  1339. // 处理图片点击
  1340. NSLog(@"点击了图片: %@", _messageModel.url);
  1341. if(_messageModel.fileError==1){
  1342. weakSelf(self);
  1343. if(weakself.bubbleCellLongPressMenuBlock){
  1344. weakself.bubbleCellLongPressMenuBlock(8);
  1345. }
  1346. return;
  1347. }
  1348. if (_messageModel.url.length == 0 && !_messageModel.isSender) {
  1349. [MBProgressHUD showWithText:@"图片正在上传"];
  1350. return;
  1351. }
  1352. [FilePreviewer.shared previewFileWithLocalPath:_messageModel.localurl remoteURL:getURL(_messageModel.url) fromViewController:self.parentViewController];
  1353. }
  1354. }
  1355. - (void)handleVideoTap {
  1356. if (_messageModel.messageType == ChatMessageTypeVideo) {
  1357. // 处理视频点击
  1358. NSLog(@"点击了视频: %@", _messageModel.url);
  1359. if(_messageModel.fileError==1){
  1360. weakSelf(self);
  1361. if(weakself.bubbleCellLongPressMenuBlock){
  1362. weakself.bubbleCellLongPressMenuBlock(8);
  1363. }
  1364. return;
  1365. }
  1366. if (_messageModel.url.length == 0 && !_messageModel.isSender) {
  1367. [MBProgressHUD showWithText:@"视频正在上传"];
  1368. return;
  1369. }
  1370. [FilePreviewer.shared previewFileWithLocalPath:self.messageModel.localurl
  1371. remoteURL:getURL(self.messageModel.url)
  1372. fromViewController:self.parentViewController];
  1373. [_messageModel downloadFileIfNeed:^(NSInteger persent) {
  1374. }];
  1375. }
  1376. }
  1377. - (void)handleFileTap {
  1378. if (_messageModel.messageType == ChatMessageTypeFile) {
  1379. // 处理视频点击
  1380. NSLog(@"点击了文件: %@", _messageModel.url);
  1381. if(_messageModel.fileError==1){
  1382. weakSelf(self);
  1383. if(weakself.bubbleCellLongPressMenuBlock){
  1384. weakself.bubbleCellLongPressMenuBlock(8);
  1385. }
  1386. return;
  1387. }
  1388. if (_messageModel.url.length == 0 && !_messageModel.isSender) {
  1389. [MBProgressHUD showWithText:@"文件正在上传"];
  1390. return;
  1391. }
  1392. UILabel *sizeLabel = _fileContentView.subviews[2];
  1393. weakSelf(self)
  1394. [_messageModel downloadFileIfNeed:^(NSInteger persent) {
  1395. dispatch_async(dispatch_get_main_queue(), ^{
  1396. sizeLabel.text = [NSString stringWithFormat:@"%ld",(long)persent];
  1397. if(persent>=100){
  1398. sizeLabel.text = weakself.messageModel.customFileSize;
  1399. [FilePreviewer.shared previewFileWithLocalPath:weakself.messageModel.localurl
  1400. remoteURL:getURL(weakself.messageModel.url)
  1401. fromViewController:weakself.parentViewController];
  1402. }
  1403. });
  1404. }];
  1405. }
  1406. }
  1407. - (void)handleVoiceTap {
  1408. if (_messageModel.messageType == ChatMessageTypeVoice) {
  1409. // 处理语音点击
  1410. NSLog(@"点击了语音: %@", _messageModel.url);
  1411. [_messageModel downloadFileIfNeed:^(NSInteger persent) {
  1412. dispatch_main_async_safe(^{
  1413. if (persent >= 100) {
  1414. [self playVoice];
  1415. }
  1416. })
  1417. }];
  1418. }
  1419. }
  1420. - (void)playVoice {
  1421. UIImageView *voiceIcon = _voiceContentView.subviews[0];
  1422. if (self.player) {
  1423. AVPlayerItem *playerItem = self.player.currentItem;
  1424. CMTime currentTime = playerItem.currentTime;
  1425. CMTime duration = playerItem.duration;
  1426. [voiceIcon stopAnimating];
  1427. if (self.player.rate == 0.0) {
  1428. if (CMTimeCompare(currentTime, duration) == 0 ||
  1429. CMTimeCompare(currentTime, duration) == 1) {
  1430. // 播放完毕
  1431. NSLog(@"Playback finished");
  1432. } else {
  1433. // 暂停
  1434. NSLog(@"Playback paused");
  1435. [self.player play];
  1436. return;
  1437. }
  1438. } else {
  1439. // 正在播放
  1440. NSLog(@"Playback in progress");
  1441. [self.player pause];
  1442. return;
  1443. }
  1444. }
  1445. NSString *urlstr = _messageModel.url;
  1446. NSURL *Url = [NSURL URLWithString:urlstr];
  1447. NSLog(@"本地路径:%@",_messageModel.localurl);
  1448. if (_messageModel.localurl && [[NSFileManager defaultManager] fileExistsAtPath:_messageModel.localurl]) {
  1449. NSLog(@"本地路径:");
  1450. urlstr=_messageModel.localurl;
  1451. Url = [NSURL fileURLWithPath:urlstr];
  1452. }
  1453. else{
  1454. }
  1455. NSLog(@"播放: %@", Url);
  1456. AVAudioSession *audioSession = [AVAudioSession sharedInstance];
  1457. [audioSession setCategory:AVAudioSessionCategoryPlayback error:nil];
  1458. [audioSession setActive:YES error:nil];
  1459. AVPlayerItem *pitem = [AVPlayerItem playerItemWithURL:Url];
  1460. //AVPlayerItem *pitem = [[AVPlayerItem alloc] initWithURL:Url];
  1461. _player = [AVPlayer playerWithPlayerItem:pitem];
  1462. [[UIDevice currentDevice] setProximityMonitoringEnabled:YES]; //建议在播放之前设置yes,播放结束设置NO。这个功能是开启红外感应
  1463. [_player play];
  1464. [[NSNotificationCenter defaultCenter] addObserver:self
  1465. selector:@selector(playerItemDidReachEnd:)
  1466. name:AVPlayerItemDidPlayToEndTimeNotification
  1467. object:pitem];
  1468. [voiceIcon startAnimating];
  1469. }
  1470. - (void)playerItemDidReachEnd:(NSNotification *)notification {
  1471. // 播放结束时的处理代码
  1472. UIImageView *voiceIcon = _voiceContentView.subviews[0];
  1473. [voiceIcon stopAnimating];
  1474. NSLog(@"播放结束:%@",notification);
  1475. [[UIDevice currentDevice] setProximityMonitoringEnabled:NO]; //建议在播放之前设置yes,播放结束设置NO。这个功能是开启红外感应
  1476. [[NSNotificationCenter defaultCenter] removeObserver:self name:notification.name object:notification.object];
  1477. //可以执行继续播放下一条操作
  1478. }
  1479. - (void)handleHistoryTap {
  1480. ChatRecordController * recordVc = [[ChatRecordController alloc] init];
  1481. for (NSDictionary * dict in _messageModel.forwardMsgArray) {
  1482. [recordVc.dataArray addObject:[ChatMessageModel modelWithDictionary:dict]];
  1483. }
  1484. UINavigationController * navi = [[UINavigationController alloc] initWithRootViewController:recordVc];
  1485. navi.modalPresentationStyle = UIModalPresentationFullScreen;
  1486. [self.parentViewController presentViewController:navi animated:YES completion:nil];
  1487. }
  1488. - (void)handleQuoteTap{
  1489. NSLog(@"handleQuoteTap----:%@",[_messageModel.quoteMessage class]);
  1490. if(![_messageModel.quoteMessage isKindOfClass:[ChatMessageModel class]]){
  1491. return;
  1492. }
  1493. if (_messageModel.quoteMessage.messageType == ChatMessageTypeText) {
  1494. QuoteDetailController * quoteDetailVc = [[QuoteDetailController alloc] init];
  1495. quoteDetailVc.quotedContent = _messageModel.quoteMessage.content;
  1496. quoteDetailVc.quotedSenderName = _messageModel.quoteMessage.nickName;
  1497. UINavigationController * navi = [[UINavigationController alloc] initWithRootViewController:quoteDetailVc];
  1498. navi.modalPresentationStyle = UIModalPresentationFullScreen;
  1499. [self.parentViewController presentViewController:navi animated:YES completion:nil];
  1500. }else if (_messageModel.quoteMessage.messageType == ChatMessageTypeImage) {
  1501. [FilePreviewer.shared previewFileWithLocalPath:_messageModel.quoteMessage.url remoteURL:getURL(_messageModel.quoteMessage.url) fromViewController:self.parentViewController];
  1502. }else if (_messageModel.quoteMessage.messageType == ChatMessageTypeVoice) {
  1503. [FilePreviewer.shared previewFileWithLocalPath:_messageModel.quoteMessage.url remoteURL:getURL(_messageModel.quoteMessage.url) fromViewController:self.parentViewController];
  1504. }else if (_messageModel.quoteMessage.messageType == ChatMessageTypeFile) {
  1505. [FilePreviewer.shared previewFileWithLocalPath:_messageModel.quoteMessage.url remoteURL:getURL(_messageModel.quoteMessage.url) fromViewController:self.parentViewController];
  1506. }else if (_messageModel.quoteMessage.messageType == ChatMessageTypeVoice) {
  1507. }
  1508. }
  1509. - (void)handleAvatarTap {
  1510. !self.avatarTapBlock?:self.avatarTapBlock(_messageModel);
  1511. }
  1512. #pragma mark - 高度计算
  1513. + (CGFloat)cellHeightForMessage:(ChatMessageModel *)message {
  1514. // 如果有缓存高度,直接返回
  1515. if (message.cellHeight > 0) {
  1516. return message.cellHeight;
  1517. }
  1518. CGFloat height = 0;
  1519. CGFloat contentHeight = 0;
  1520. CGFloat horizontalMargin = 12.0f;
  1521. CGFloat verticalMargin = 10.0f;
  1522. CGFloat maxWidth = kContentMaxWidth - 2 * horizontalMargin;
  1523. // 计算内容高度
  1524. switch (message.messageType) {
  1525. case ChatMessageTypeText: {
  1526. NSString *text = message.content ?: @"";
  1527. UIFont *font = [UIFont systemFontOfSize:17]; // 设置字体大小
  1528. CGSize maximumSize = CGSizeMake(maxWidth, CGFLOAT_MAX); // 设置最大宽度,高度设为CGFLOAT_MAX表示不限制高度
  1529. NSDictionary *attributes = @{NSFontAttributeName: font};
  1530. CGRect rect = [text boundingRectWithSize:maximumSize
  1531. options:NSStringDrawingUsesLineFragmentOrigin
  1532. attributes:attributes
  1533. context:nil];
  1534. CGFloat height = rect.size.height;
  1535. contentHeight = height + 2 * verticalMargin;
  1536. contentHeight = MAX(contentHeight, kMinBubbleHeight);
  1537. if (message.quoteMessage) {
  1538. contentHeight = contentHeight + 30;
  1539. }
  1540. break;
  1541. }
  1542. case ChatMessageTypeImage:
  1543. case ChatMessageTypeVideo: {
  1544. CGSize mediaSize = [self otherAdjustMediaSize:message.mediaSize];
  1545. contentHeight = mediaSize.height;
  1546. break;
  1547. }
  1548. case ChatMessageTypeFile:
  1549. contentHeight = 60.0f;
  1550. break;
  1551. case ChatMessageTypeCallBack:
  1552. contentHeight = 20.f;
  1553. break;
  1554. case ChatMessageTypeVoice:
  1555. contentHeight = 30.0f;
  1556. break;
  1557. case ChatMessageTypeCall:
  1558. contentHeight = 40.0f;
  1559. break;
  1560. case ChatMessageTypeHistory:
  1561. contentHeight = 80.0f;
  1562. break;
  1563. case ChatMessageTypeEvent:
  1564. contentHeight = 20.f;
  1565. break;
  1566. case ChatMessageTypeCallBack2:
  1567. contentHeight = 20.f;
  1568. break;
  1569. case ChatMessageTypeDel:
  1570. contentHeight = 20.f;
  1571. break;
  1572. }
  1573. // 总高度 = 内容高度 + 上下边距
  1574. height = contentHeight + kBubbleTopMargin+kBubbleBottomMargin;
  1575. // 缓存高度
  1576. message.cellHeight = height;
  1577. return height;
  1578. }
  1579. + (void)precalculateHeightForMessage:(ChatMessageModel *)message completion:(void(^)(CGFloat height))completion {
  1580. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  1581. CGFloat height = [self cellHeightForMessage:message];
  1582. dispatch_async(dispatch_get_main_queue(), ^{
  1583. if (completion) completion(height);
  1584. });
  1585. });
  1586. }
  1587. @end