chatCellView.m 70 KB

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