chatCellView.m 70 KB

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