chatCellView.m 71 KB

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