chatCellView.m 71 KB

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