QMChatRoomViewController.m 53 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312
  1. //
  2. // QMChatRoomViewController.m
  3. // IMSDK-OC
  4. //
  5. // Created by HCF on 16/3/9.
  6. // Copyright © 2016年 HCF. All rights reserved.
  7. //
  8. #import "QMChatRoomViewController.h"
  9. #import "QMChatRoomInputView.h"
  10. #import "TCMessageManagerFaceView.h"
  11. #import "QMChatRoomMoreView.h"
  12. #import <QMLineSDK/QMLineSDK.h>
  13. #import <QMLineSDK/QMLineSDK.h>
  14. #import "QMRecordIndicatorView.h"
  15. #import "MJRefresh.h"
  16. #import "TZImagePickerController.h"
  17. #import "QMChatRoomShowImageController.h"
  18. #import "QMProfileManager.h"
  19. #import "QMTapGestureRecognizer.h"
  20. #import "QMChatRoomGuestBookViewController.h"
  21. #import "QMChatRoomRobotCell.h"
  22. #import "QMChatRoomTextCell.h"
  23. #import "QMChatRoomVoiceCell.h"
  24. #import "QMChatRoomImageCell.h"
  25. #import "QMChatRoomInvestigateCell.h"
  26. #import "QMChatRoomFileCell.h"
  27. #import "QMChatRoomIframeCell.h"
  28. #import "QMChatRoomCellFactory.h"
  29. #import "QMChatRoomRichTextCell.h"
  30. #import "QMChatRoomNoteCell.h"
  31. #import "QMChatRoomMp3Cell.h"
  32. #import "QMChatRoomCardCell.h"
  33. #import "QMAudioPlayer.h"
  34. #import "QMAudioRecorder.h"
  35. #import "SJVoiceTransform.h"
  36. //new
  37. #import "QMChatTileView.h"
  38. #import "QMFileManagerController.h"
  39. #import "QMAlert.h"
  40. #import "QMTextAttachment.h"
  41. #import "NSAttributedString+QMEmojiExtension.h"
  42. #import <Photos/Photos.h>
  43. #import "Reachability.h"
  44. #import "QMTextModel.h"
  45. /**
  46. 在线客服聊天界面
  47. */
  48. @interface QMChatRoomViewController ()<UITableViewDataSource, UITableViewDelegate, UITextViewDelegate, TCMessageManagerFaceViewDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate,UIAlertViewDelegate, AVAudioRecorderDelegate, QMKServiceDelegate, QMAudioRecorderDelegate> {
  49. NSMutableArray * _dataArray;
  50. NSArray * _investigateArray;
  51. int _dataNum;
  52. CGFloat _keyboardHigh;
  53. QMChatTileView *_titleView;
  54. NSTimer *breakTimer;
  55. NSTimer *breakTipTimer;
  56. NSTimer *backStatus;
  57. CGFloat _navHeight;
  58. NSString *_titleViewText;
  59. }
  60. @property (nonatomic, assign)float upProgress;
  61. @end
  62. @implementation QMChatRoomViewController
  63. #pragma mark - 生命周期
  64. // 注册通知
  65. -(instancetype)init {
  66. self = [super init];
  67. if (self) {
  68. // 建议使用willshow和willhide
  69. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardFrameChange:) name:UIKeyboardWillChangeFrameNotification object:nil];
  70. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(getNewReload:) name:CHATMSG_RELOAD object:nil];
  71. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(robotAction) name:ROBOT_SERVICE object:nil];
  72. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(customOnline) name:CUSTOMSRV_ONLINE object:nil];
  73. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(customOffline) name:CUSTOMSRV_OFFLINE object:nil];
  74. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(customClaim) name:CUSTOMSRV_CLAIM object:nil];
  75. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(customFinish) name:CUSTOMSRV_FINISH object:nil];
  76. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(customQueue:) name:CUSTOMSRV_QUEUENUM object:nil];
  77. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(customAgentMessage:) name:CUSTOMSRV_AGENT object:nil];
  78. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(customInvestigate) name:CUSTOMSRV_INVESTIGATE object:nil];
  79. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(customVIP) name:CUSTOMSRV_VIP object:nil];
  80. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(customLeavemsg:) name:CUSTOMSRV_LEAVEMSG object:nil];
  81. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(changeCustomStatus) name:CUSTOMSRV_IMPORTING object:nil];
  82. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(cbangeDrowMessageStatus:) name:CUSTOMSRV_DRAWMESSAGE object:nil];
  83. }
  84. return self;
  85. }
  86. // 基本配置
  87. - (void)viewWillAppear:(BOOL)animated {
  88. self.navigationController.navigationBarHidden = NO;
  89. self.navigationController.navigationBar.barTintColor = [UIColor colorWithRed:246/255.0 green:248/255.0 blue:249/255.0 alpha:1.0];
  90. self.navigationController.navigationBar.tintColor = [UIColor colorWithRed:13/255.0 green:139/255.0 blue:249/255.0 alpha:1];
  91. [self.navigationController.navigationBar setTranslucent:NO];
  92. self.navigationController.interactivePopGestureRecognizer.delaysTouchesBegan = NO;
  93. }
  94. /**
  95. 开始会话
  96. peer: 技能组id 必传
  97. params: @{@"agent":@"8000"} 专属坐席
  98. @{@"customField":@{@"姓名":@"李三"}} 自定义字段
  99. */
  100. - (void)viewDidAppear:(BOOL)animated {
  101. if (self.isPush == NO) {
  102. __weak QMChatRoomViewController * myChatView = self;
  103. if (self.isOpenSchedule) {
  104. NSLog(@"sdk走日程管理方法");
  105. [QMConnect sdkBeginNewChatSessionSchedule: self.scheduleId processId: self.processId currentNodeId: self.currentNodeId entranceId: self.entranceId params: @{@"":@""} successBlock:^(BOOL remark, NSString *str) {
  106. NSLog(@"开始会话成功");
  107. dispatch_async(dispatch_get_main_queue(), ^{
  108. // 是否启动了评价功能
  109. if (remark == NO) {
  110. myChatView.addView.evaluateBtn.hidden = YES;
  111. myChatView.addView.evaluateLabel.hidden = YES;
  112. }else {
  113. myChatView.addView.evaluateBtn.hidden = NO;
  114. myChatView.addView.evaluateLabel.hidden = NO;
  115. }
  116. });
  117. } failBlock:^(NSString *str) {
  118. NSLog(@"开始会话失败, %@" , str);
  119. }];
  120. }else{
  121. NSLog(@"sdk走技能组方法");
  122. [QMConnect sdkBeginNewChatSession:self.peerId params:@{@"customField":@{@"1111":@"2222",@"3333":@"4444"},@"agent":@"8129"} successBlock:^(BOOL remark, NSString *str) {
  123. NSLog(@"开始会话成功");
  124. dispatch_async(dispatch_get_main_queue(), ^{
  125. // 是否启动了评价功能
  126. if (remark == NO) {
  127. myChatView.addView.evaluateBtn.hidden = YES;
  128. myChatView.addView.evaluateLabel.hidden = YES;
  129. }else {
  130. myChatView.addView.evaluateBtn.hidden = NO;
  131. myChatView.addView.evaluateLabel.hidden = NO;
  132. }
  133. });
  134. } failBlock:^(NSString *str) {
  135. NSLog(@"开始会话失败, %@" , str);
  136. }];
  137. }
  138. self.isPush = YES;
  139. }
  140. }
  141. - (void)viewDidLoad {
  142. [super viewDidLoad];
  143. self.view.backgroundColor = [UIColor colorWithRed:240/255.0 green:240/255.0 blue:240/255.0 alpha:1];
  144. [self createUI];
  145. //判断是否是机器人(默认是关闭的)
  146. if (![QMConnect allowRobot]) {
  147. // [self insertCardInfoMessage];
  148. }
  149. /**
  150. 创建文件管理类
  151. name: 可随便填写
  152. password: 可随便填写
  153. */
  154. QMProfileManager *manger = [QMProfileManager sharedInstance];
  155. [manger loadProfile:@"name" password:@"123456"];
  156. // 网络监控
  157. Reachability *hostReach = [Reachability reachabilityForInternetConnection];
  158. hostReach.reachableBlock = ^(Reachability *reachability) {
  159. dispatch_async(dispatch_get_main_queue(), ^{
  160. // 网络连接
  161. });
  162. };
  163. hostReach.unreachableBlock = ^(Reachability *reachability) {
  164. dispatch_async(dispatch_get_main_queue(), ^{
  165. // 网络断开
  166. });
  167. };
  168. [hostReach startNotifier];
  169. [self getInvestigateData];
  170. _dataArray = [[NSMutableArray alloc]init];
  171. if (_dataNum == 0) {
  172. _dataNum = 10;
  173. }
  174. [self getData];
  175. [self.chatTableView reloadData];
  176. dispatch_async(dispatch_get_main_queue(), ^{
  177. [self scrollToEnd];
  178. });
  179. [self createNSTimer];
  180. self.heightCaches = [NSMutableDictionary dictionary];
  181. }
  182. - (void)viewWillDisappear:(BOOL)animated {
  183. if ([self.chatInputView.inputView isFirstResponder]) {
  184. [self.chatInputView.inputView resignFirstResponder];
  185. self.chatInputView.inputView.inputView = nil;
  186. }
  187. [self.navigationController.navigationBar setTranslucent:YES];
  188. }
  189. - (void)viewDidDisappear:(BOOL)animated {
  190. NSLog(@"Appear");
  191. }
  192. // 移除通知
  193. - (void)dealloc {
  194. NSLog(@"销毁");
  195. [[NSNotificationCenter defaultCenter] removeObserver:self];
  196. }
  197. #pragma mark - 创建聊天室UI(消息列表、输入工具条、提示窗...)
  198. - (void)createUI {
  199. self.view.backgroundColor = [UIColor whiteColor];
  200. CGRect StatusRect = [[UIApplication sharedApplication] statusBarFrame];
  201. CGRect NavRect = self.navigationController.navigationBar.frame;
  202. _navHeight = StatusRect.size.height + NavRect.size.height;
  203. // 坐席信息提示
  204. _titleView = [[QMChatTileView alloc] initWithFrame: CGRectMake(0, 0, 150, 40)];
  205. _titleView.nameLabel.text = NSLocalizedString(@"title.people", nil);
  206. _titleView.stateInfoLabel.text = NSLocalizedString(@"title.connection", nil);
  207. _titleView.intrinsicContentSize = CGSizeMake(150, 40);
  208. self.navigationItem.titleView = _titleView;
  209. // 消息列表
  210. self.chatTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight-kInputViewHeight-_navHeight) style:UITableViewStylePlain];
  211. self.chatTableView.delegate = self;
  212. self.chatTableView.dataSource = self;
  213. self.chatTableView.backgroundColor = [UIColor colorWithRed:240/255.0 green:240/255.0 blue:240/255.0 alpha:1];
  214. self.chatTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
  215. self.chatTableView.estimatedRowHeight = 0;
  216. [self.view addSubview:self.chatTableView];
  217. __weak QMChatRoomViewController * myChatView = self;
  218. MJRefreshNormalHeader *mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
  219. [myChatView Refresh];
  220. }];
  221. [mj_header.lastUpdatedTimeLabel setHidden:true];
  222. self.chatTableView.mj_header = mj_header;
  223. // 输入工具条
  224. self.chatInputView = [[QMChatRoomInputView alloc] initWithFrame:CGRectMake(0, kScreenHeight-kInputViewHeight-_navHeight, kScreenWidth, kInputViewHeight)];
  225. [self.chatInputView.voiceButton addTarget:self action:@selector(voiceBtnAction:) forControlEvents:UIControlEventTouchUpInside];
  226. [self.chatInputView.faceButton addTarget:self action:@selector(faceBtnAction:) forControlEvents:UIControlEventTouchUpInside];
  227. [self.chatInputView.addButton addTarget:self action:@selector(addBtnAction:) forControlEvents:UIControlEventTouchUpInside];
  228. [self.chatInputView.RecordBtn addTarget:self action:@selector(cancelRecord:) forControlEvents:UIControlEventTouchUpOutside];
  229. [self.chatInputView.RecordBtn addTarget:self action:@selector(RecordBtnBegin:) forControlEvents:UIControlEventTouchDown];
  230. [self.chatInputView.RecordBtn addTarget:self action:@selector(RecordBtnEnd:) forControlEvents:UIControlEventTouchUpInside];
  231. [self.chatInputView.RecordBtn addTarget:self action:@selector(RecordBtnExit:) forControlEvents:UIControlEventTouchDragExit];
  232. [self.chatInputView.RecordBtn addTarget:self action:@selector(RecordBtnEnter:) forControlEvents:UIControlEventTouchDragEnter];
  233. self.chatInputView.inputView.delegate = self;
  234. [self.view addSubview:self.chatInputView];
  235. // 表情面板
  236. self.faceView = [[TCMessageManagerFaceView alloc] initWithFrame:CGRectMake(0, [UIScreen mainScreen].bounds.size.height, kScreenWidth, QM_IS_IPHONEX ? 250 : 216)];
  237. self.faceView.delegate = self;
  238. [self.faceView.sendButton addTarget:self action:@selector(sendBtnAction:) forControlEvents:UIControlEventTouchUpInside];
  239. // 扩展面板
  240. self.addView = [[QMChatRoomMoreView alloc] initWithFrame:CGRectMake(0, [UIScreen mainScreen].bounds.size.height, kScreenWidth, QM_IS_IPHONEX ? 144 : 110)];
  241. [self.addView.takePicBtn addTarget:self action:@selector(takePicBtnAction) forControlEvents:UIControlEventTouchUpInside];
  242. [self.addView.evaluateBtn addTarget:self action:@selector(evaluateBtnAction) forControlEvents:UIControlEventTouchUpInside];
  243. [self.addView.takeFileBtn addTarget:self action:@selector(takeFileBtnAction) forControlEvents:UIControlEventTouchUpInside];
  244. // 转人工
  245. self.manualButotn = [UIButton buttonWithType:UIButtonTypeSystem];
  246. self.manualButotn.frame = CGRectMake(0, 0, 60, 30);
  247. self.manualButotn.titleLabel.font = [UIFont systemFontOfSize:16];
  248. [self.manualButotn setTitle: NSLocalizedString(@"button.topeople", nil) forState:UIControlStateNormal];
  249. [self.manualButotn setTitleColor:[UIColor colorWithRed:13/255.0 green:139/255.0 blue:249/255.0 alpha:1] forState:UIControlStateNormal];
  250. [self.manualButotn addTarget:self action:@selector(customClick) forControlEvents:UIControlEventTouchUpInside];
  251. if ([QMConnect allowRobot]) {
  252. self.isRobot = true;
  253. self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:self.manualButotn];
  254. }else {
  255. self.isRobot = false;
  256. }
  257. // 注销
  258. self.logoutButton = [UIButton buttonWithType:UIButtonTypeSystem];
  259. self.logoutButton.frame = CGRectMake(0, 0, 50, 30);
  260. self.logoutButton.titleLabel.font = [UIFont systemFontOfSize:16];
  261. [self.logoutButton setTitle:NSLocalizedString(@"button.logout", nil) forState:UIControlStateNormal];
  262. [self.logoutButton setTitleColor:[UIColor colorWithRed:13/255.0 green:139/255.0 blue:249/255.0 alpha:1] forState:UIControlStateNormal];
  263. [self.logoutButton addTarget:self action:@selector(logoutAction) forControlEvents:UIControlEventTouchUpInside];
  264. self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:self.logoutButton];
  265. self.indicatorView = [[QMRecordIndicatorView alloc] init];
  266. self.indicatorView.frame = CGRectMake((kScreenWidth-150)/2, (kScreenHeight-150-_navHeight-50)/2, 150, 150);
  267. UITapGestureRecognizer * gestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(hideKeyboard)];
  268. [self.chatTableView addGestureRecognizer:gestureRecognizer];
  269. gestureRecognizer.cancelsTouchesInView = NO;
  270. }
  271. - (void)hideKeyboard {
  272. [self.chatInputView.inputView resignFirstResponder];
  273. self.chatInputView.inputView.inputView = nil;
  274. }
  275. #pragma mark - 获取数据(数据模型已存储本地)
  276. // 获取消息数据
  277. - (void)getData {
  278. _dataArray = [NSMutableArray arrayWithArray:[QMConnect getDataFromDatabase:_dataNum]];
  279. /**
  280. 获取同一个accessid(AppKey)下的全部信息 用下面此接口
  281. _dataArray = [NSMutableArray arrayWithArray:[QMConnect getAccessidAllDataFormDatabase:_dataNum]];
  282. */
  283. /**
  284. 获取同一个userId下的全部信息 用下面此接口
  285. _dataArray = [NSMutableArray arrayWithArray:[QMConnect getUserIdDataFormDatabase:_dataNum]];
  286. */
  287. }
  288. // 获取后台配置信息 、 满意度调查 、回复超时时间
  289. - (void)getInvestigateData {
  290. [QMConnect sdkGetInvestigate:^(NSArray * _Nonnull investigateArray) {
  291. dispatch_async(dispatch_get_main_queue(), ^{
  292. _investigateArray = investigateArray;
  293. });
  294. } failureBlock:^{
  295. dispatch_async(dispatch_get_main_queue(), ^{
  296. _investigateArray = [NSArray array];
  297. });
  298. }];
  299. }
  300. // 刷新TableView
  301. -(void)reloadTableView {
  302. if (_titleViewText != nil) {
  303. _titleView.stateInfoLabel.text = _titleViewText;
  304. }
  305. NSLog(@"刷新信息");
  306. [self.chatTableView reloadData];
  307. dispatch_async(dispatch_get_main_queue(), ^{
  308. [self scrollToEnd];
  309. });
  310. }
  311. /**
  312. 新消息通知、发送和接收的消息 都会走这个通知 统一刷新聊天界面
  313. */
  314. - (void)getNewReload: (NSNotification *)sender {
  315. NSLog(@"获取到新消息 %@", sender.object);
  316. [self getData];
  317. [self reloadTableView];
  318. if (backStatus.isValid) {
  319. [backStatus invalidate];
  320. }
  321. }
  322. // 滑动到底部
  323. - (void)scrollToEnd {
  324. if (_dataArray.count>0) {
  325. [_chatTableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:_dataArray.count-1 inSection:0] atScrollPosition:UITableViewScrollPositionNone animated:NO];
  326. }
  327. }
  328. // 下拉刷新
  329. - (void)Refresh {
  330. if (_dataNum>_dataArray.count) {
  331. }
  332. _dataNum = _dataNum+10;
  333. [self getData];
  334. [_chatTableView reloadData];
  335. [self.chatTableView.mj_header endRefreshing];
  336. }
  337. //商品信息的卡片(默认是关闭的,需要手动打开注释)
  338. - (void)insertCardInfoMessage {
  339. [QMConnect deleteCardTypeMessage];
  340. NSMutableDictionary *dic = [[NSMutableDictionary alloc] init];
  341. [dic setObject:@"https://fs-km.7moor.com/N00000000143/km/2018-06-15/1529044921332/35522b40-7067-11e8-ab29-a3347bfc2358" forKey:@"cardImage"]; //此参数需要填写的是URL
  342. [dic setObject:@"标题" forKey:@"cardHeader"];
  343. [dic setObject:@"副标题" forKey:@"cardSubhead"];
  344. [dic setObject:@"价格" forKey:@"cardPrice"];
  345. [dic setObject:@"https://kf.7moor.com" forKey:@"cardUrl"]; //此参数需要填写的是URL
  346. [QMConnect insertCardInfoData:dic type:@""];
  347. [self getData];
  348. [self reloadTableView];
  349. }
  350. - (void)applicationWillResignActive {
  351. NSLog(@"退到后台");
  352. }
  353. - (void)applicationDidBecomeActive {
  354. NSLog(@"返回前台");
  355. }
  356. #pragma mark - TableViewDelegate TableViewDataSource
  357. - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
  358. return _dataArray.count;
  359. }
  360. - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
  361. CustomMessage * message = _dataArray[_dataArray.count-indexPath.row-1];
  362. NSString * identifier = @"";
  363. if ([message.messageType isEqualToString:@"text"]) {
  364. if ([message.isRobot isEqualToString:@"1"]) {
  365. identifier = NSStringFromClass([QMChatRoomRobotCell class]);
  366. }else {
  367. identifier = NSStringFromClass([QMChatRoomTextCell class]);
  368. }
  369. }else if ([message.messageType isEqualToString:@"voice"]) {
  370. identifier = NSStringFromClass([QMChatRoomVoiceCell class]);
  371. }else if ([message.messageType isEqualToString:@"image"]) {
  372. identifier = NSStringFromClass([QMChatRoomImageCell class]);
  373. }else if ([message.messageType isEqualToString:@"investigate"]) {
  374. identifier = NSStringFromClass([QMChatRoomInvestigateCell class]);
  375. }else if ([message.messageType isEqualToString:@"file"]) {
  376. if ([message.fileName.pathExtension.lowercaseString isEqual: @"mp3"]) {
  377. identifier = NSStringFromClass([QMChatRoomMp3Cell class]);//MP3文件以语音形式播放
  378. }else{
  379. identifier = NSStringFromClass([QMChatRoomFileCell class]);
  380. }
  381. }else if ([message.messageType isEqualToString:@"iframe"]) {
  382. identifier = NSStringFromClass([QMChatRoomIframeCell class]);
  383. }else if ([message.messageType isEqualToString:@"richText"]){
  384. identifier = NSStringFromClass([QMChatRoomRichTextCell class]);
  385. }else if ([message.messageType isEqualToString:@"withdrawMessage"]) {
  386. identifier = NSStringFromClass([QMChatRoomNoteCell class]);
  387. }else if ([message.messageType isEqualToString:@"card"]){
  388. identifier = NSStringFromClass([QMChatRoomCardCell class]);
  389. }else if ([message.messageType isEqualToString:@"cardInfo"]) {
  390. identifier = NSStringFromClass([QMChatRoomRichTextCell class]);
  391. }else {
  392. identifier = NSStringFromClass([QMChatRoomTextCell class]);
  393. }
  394. QMChatRoomBaseCell * cell = [tableView dequeueReusableCellWithIdentifier:identifier];
  395. if (cell == nil) {
  396. cell = [QMChatRoomCellFactory createCellWithClassName:identifier cellModel:message indexPath:indexPath];
  397. }
  398. if (indexPath.row>0) {
  399. CustomMessage * preMessage = _dataArray[_dataArray.count-indexPath.row];
  400. UInt64 disTime = message.createdTime.longLongValue - preMessage.createdTime.longLongValue;
  401. if (disTime<3*60*1000) {
  402. cell.timeLabel.hidden = YES;
  403. }else {
  404. cell.timeLabel.hidden = NO;
  405. }
  406. }else {
  407. cell.timeLabel.hidden = NO;
  408. }
  409. cell.selectionStyle = UITableViewCellSelectionStyleNone;
  410. // 如果需要设置头像、该方法加上一个头像路径参数
  411. [cell setData:message avater:self.avaterStr];
  412. if ([message.messageType isEqualToString:@"file"]) {
  413. [cell setProgress: self.upProgress];
  414. }
  415. if ([message.messageType isEqualToString:@"text"]) {
  416. cell.tapNetAddress = ^(NSString *address) {
  417. if ([address rangeOfString:@"http://"].location == NSNotFound && [address rangeOfString:@"https://"].location == NSNotFound) {
  418. address = [NSString stringWithFormat:@"http://%@", address];
  419. }
  420. [[UIApplication sharedApplication] openURL:[NSURL URLWithString:address]];
  421. };
  422. }
  423. // 机器人消息可以选择问题代码 答案可以选择有帮助或无帮助
  424. if ([message.messageType isEqualToString:@"text"] && [message.isRobot isEqualToString:@"1"]) {
  425. __weak QMChatRoomViewController *weakSelf = self;
  426. cell.tapSendMessage = ^(NSString *text) {
  427. [weakSelf sendText:text];
  428. };
  429. cell.didBtnAction = ^(BOOL isUseful) {
  430. if (!message.isUseful||[message.isUseful isEqualToString:@"none"]) {
  431. if ([weakSelf.heightCaches objectForKey:message._id]) {
  432. [weakSelf.heightCaches removeObjectForKey:message._id];
  433. }
  434. [weakSelf sendRobotFeedback:isUseful questionId:message.questionId messageId:message._id robotType:message.robotType robotId:message.robotId robotMsgId:message.robotMsgId];
  435. }
  436. };
  437. }
  438. return cell;
  439. }
  440. - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
  441. CustomMessage * message = _dataArray[_dataArray.count-indexPath.row-1];
  442. if ([message.messageType isEqualToString:@"withdrawMessage"]) {
  443. }else if ([message.messageType isEqualToString:@"cardInfo"]) {
  444. }else{
  445. // 取已有cell高度 时间高度计算
  446. if ([self.heightCaches objectForKey:message._id] && indexPath.row != 0) {
  447. NSNumber *tmpHeight = [self.heightCaches objectForKey:message._id];
  448. return tmpHeight.doubleValue;
  449. }
  450. }
  451. CGFloat height = 15;
  452. if (indexPath.row>0) {
  453. CustomMessage * preMessage = _dataArray[_dataArray.count-indexPath.row];
  454. UInt64 disTime = message.createdTime.longLongValue - preMessage.createdTime.longLongValue;
  455. if (disTime<3*60*1000) {
  456. height = 15;
  457. }else {
  458. height = 45;
  459. }
  460. }else {
  461. height = 45;
  462. }
  463. if ([message.messageType isEqualToString:@"text"]) {
  464. if ([message.isRobot isEqualToString:@"1"]) {
  465. CGFloat robotHeight = [QMTextModel calcRobotHeight:message.message];
  466. height += (robotHeight+5+21);
  467. }else {
  468. CGFloat textHeight = [QMTextModel calcTextHeight:message.message];
  469. height += (textHeight+5+21);
  470. }
  471. height = height>65?height:65;
  472. if ([message.isRobot isEqualToString:@"1"] && ![message.questionId isEqualToString:@""]) {
  473. if (message.isUseful) {
  474. if ([message.isUseful isEqualToString:@"none"]) {
  475. height += 30;
  476. }else {
  477. height += 60;
  478. }
  479. }else {
  480. height += 30;
  481. }
  482. }
  483. }else if ([message.messageType isEqualToString:@"voice"]) {
  484. height += 45;
  485. }else if ([message.messageType isEqualToString:@"image"]) {
  486. height += 140;
  487. }else if ([message.messageType isEqualToString:@"investigate"]) {
  488. height += 145;
  489. }else if ([message.messageType isEqualToString:@"file"]) {
  490. height += 50;
  491. }else if ([message.messageType isEqualToString:@"iframe"]) {
  492. height += message.height.intValue+30;
  493. }else if ([message.messageType isEqualToString:@"richText"]) {
  494. height += 120;
  495. }else if ([message.messageType isEqualToString:@"withdrawMessage"]) {
  496. height = 45;
  497. }else if ([message.messageType isEqualToString:@"card"]) {
  498. height += 150;
  499. }else if ([message.messageType isEqualToString:@"cardInfo"]) {
  500. height += 80;
  501. }else {
  502. height += 45;
  503. }
  504. // 存储cell高度 如果高度有变化 请提前清除对应id的缓存
  505. NSNumber *number = [NSNumber numberWithDouble:height];
  506. [self.heightCaches setObject:number forKey:message._id];
  507. return height;
  508. }
  509. #pragma mark - InputView Action
  510. //切换录音按钮
  511. - (void)voiceBtnAction:(UIButton *)button {
  512. if (self.chatInputView.RecordBtn.hidden == YES) {
  513. [self.chatInputView showRecordButton:YES];
  514. [self.chatInputView.inputView endEditing:YES];
  515. }else {
  516. [self.chatInputView showRecordButton:NO];
  517. self.chatInputView.inputView.inputView = nil;
  518. [self.chatInputView.inputView becomeFirstResponder];
  519. [self.chatInputView.inputView reloadInputViews];
  520. }
  521. }
  522. //表情按钮
  523. - (void)faceBtnAction:(UIButton *)button {
  524. if (button.tag == 1) {
  525. [self.chatInputView showEmotionView:YES];
  526. self.chatInputView.inputView.inputView = self.faceView;
  527. }else {
  528. [self.chatInputView showEmotionView:NO];
  529. self.chatInputView.inputView.inputView = nil;
  530. }
  531. [self.chatInputView.inputView becomeFirstResponder];
  532. [self.chatInputView.inputView reloadInputViews];
  533. }
  534. //扩展功能按钮
  535. - (void)addBtnAction:(UIButton *)button {
  536. if (button.tag == 3) {
  537. [self.chatInputView showMoreView:YES];
  538. self.chatInputView.inputView.inputView = self.addView;
  539. [self.chatInputView.inputView becomeFirstResponder];
  540. [self.chatInputView.inputView reloadInputViews];
  541. }else {
  542. [self.chatInputView showMoreView:NO];
  543. self.chatInputView.inputView.inputView = nil;
  544. [self.chatInputView.inputView endEditing:YES];
  545. }
  546. }
  547. #pragma mark - Record Action
  548. // 开始录音
  549. - (void)RecordBtnBegin:(UIButton *)button {
  550. NSString *fileName = [[NSUUID new] UUIDString];
  551. // 验证权限
  552. AVAuthorizationStatus authorizationStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeAudio];
  553. switch (authorizationStatus) {
  554. case AVAuthorizationStatusNotDetermined:
  555. [AVCaptureDevice requestAccessForMediaType:AVMediaTypeAudio completionHandler:^(BOOL granted) {
  556. }];
  557. break;
  558. case AVAuthorizationStatusAuthorized:
  559. self.indicatorView.isCount = false;
  560. [self.indicatorView changeViewStatus:QMIndicatorStatusNormal];
  561. [self.view addSubview:self.indicatorView];
  562. [self changeButtonStatus:YES];
  563. [[QMAudioRecorder sharedInstance] startAudioRecord:fileName maxDuration:60.0 delegate:self];
  564. break;
  565. case AVAuthorizationStatusRestricted:
  566. NSLog(@"麦克风访问受限!");
  567. break;
  568. case AVAuthorizationStatusDenied:
  569. NSLog(@"设置允许访问麦克风");
  570. break;
  571. }
  572. }
  573. // 结束录音
  574. - (void)RecordBtnEnd:(UIButton *)button {
  575. [[QMAudioRecorder sharedInstance] stopAudioRecord];
  576. }
  577. // 取消录音
  578. - (void)cancelRecord: (UIButton *)button {
  579. [[QMAudioRecorder sharedInstance] cancelAudioRecord];
  580. [self.indicatorView removeFromSuperview];
  581. [self changeButtonStatus:NO];
  582. }
  583. - (void)RecordBtnExit: (UIButton *)button {
  584. [self.indicatorView changeViewStatus:QMIndicatorStatusCancel];
  585. }
  586. - (void)RecordBtnEnter: (UIButton *)button {
  587. [self.indicatorView changeViewStatus:QMIndicatorStatusNormal];
  588. }
  589. // 更改按钮状态
  590. - (void)changeButtonStatus:(BOOL)down {
  591. if (down == YES) {
  592. [self.chatInputView.RecordBtn setTitle:NSLocalizedString(@"button.recorder_recording", nil) forState:UIControlStateNormal];
  593. [self.chatInputView.RecordBtn setTitleColor:[UIColor colorWithRed:50/255.0f green:167/255.0f blue:255/255.0f alpha:1.0] forState:UIControlStateNormal];
  594. self.chatInputView.RecordBtn.layer.borderColor = [[UIColor colorWithRed:50/255.0f green:167/255.0f blue:255/255.0f alpha:1.0] CGColor];
  595. [self.chatInputView.RecordBtn setTintColor:[UIColor colorWithRed:50/255.0f green:167/255.0f blue:255/255.0f alpha:1.0]];
  596. }else {
  597. [self.chatInputView.RecordBtn setTitle:NSLocalizedString(@"button.recorder_normal", nil) forState:UIControlStateNormal];
  598. [self.chatInputView.RecordBtn setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
  599. self.chatInputView.RecordBtn.layer.borderColor = [[UIColor grayColor] CGColor];
  600. }
  601. }
  602. - (void)audioRecorderStart {
  603. }
  604. - (void)audioRecorderCompletion:(NSString *)fileName duration:(NSString *)duration {
  605. NSString * path = [NSString stringWithFormat:@"%@/%@/%@",NSHomeDirectory(),@"Documents",fileName];
  606. [SJVoiceTransform stransformToMp3ByUrlWithUrl:path];
  607. [self sendAudio:fileName duration:duration];
  608. if (duration.intValue >= 60) {
  609. [self.indicatorView changeViewStatus:QMIndicatorStatusLong];
  610. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
  611. [self.indicatorView removeFromSuperview];
  612. [self changeButtonStatus:NO];
  613. });
  614. }else {
  615. [self.indicatorView removeFromSuperview];
  616. [self changeButtonStatus:NO];
  617. }
  618. }
  619. - (void)audioRecorderChangeInTimer:(NSTimeInterval)power total:(int)count {
  620. [self.indicatorView updateImageWithPower:power];
  621. self.indicatorView.count = count;
  622. }
  623. - (void)audioRecorderCancel {
  624. [self.indicatorView removeFromSuperview];
  625. [self changeButtonStatus:NO];
  626. }
  627. - (void)audioRecorderFail {
  628. [self.indicatorView changeViewStatus:QMIndicatorStatusShort];
  629. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
  630. [self.indicatorView removeFromSuperview];
  631. [self changeButtonStatus:NO];
  632. });
  633. }
  634. #pragma mark - MoreView Action
  635. //通过摄像头获取图片
  636. - (void)photoBtnAction {
  637. if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
  638. UIImagePickerController * imagePicker = [[UIImagePickerController alloc] init];
  639. imagePicker.delegate = self;
  640. imagePicker.allowsEditing = NO;
  641. imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera;
  642. imagePicker.modalPresentationStyle = UIModalPresentationFullScreen;
  643. [self presentViewController:imagePicker animated:YES completion:nil];
  644. }
  645. }
  646. //相机代理方法
  647. - (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
  648. if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
  649. UIImage * myImage = [info objectForKey:UIImagePickerControllerOriginalImage];
  650. [picker dismissViewControllerAnimated:YES completion:nil];
  651. UIImageWriteToSavedPhotosAlbum(myImage, nil, nil, nil);
  652. [self sendImage:myImage];
  653. }
  654. }
  655. //从相册获取图片
  656. - (void)takePicBtnAction {
  657. TZImagePickerController *imagePickerVc = [[TZImagePickerController alloc] initWithMaxImagesCount:5 delegate:nil];
  658. [imagePickerVc setDidFinishPickingPhotosHandle:^(NSArray<UIImage *> *photos, NSArray *assets, BOOL isStop) {
  659. for (UIImage *image in photos) {
  660. [self sendImage:image];
  661. }
  662. }];
  663. imagePickerVc.modalPresentationStyle = UIModalPresentationFullScreen;
  664. [self presentViewController:imagePickerVc animated:YES completion:nil];
  665. }
  666. // 获取文件
  667. - (void)takeFileBtnAction {
  668. QMFileManagerController * fileViewController = [[QMFileManagerController alloc] init];
  669. [self.navigationController pushViewController:fileViewController animated:true];
  670. }
  671. // 满意度评价
  672. - (void)evaluateBtnAction {
  673. UIAlertController * investigateAlertView = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"button.chat_evaluate", nil) message:nil preferredStyle:UIAlertControllerStyleAlert];
  674. for (NSDictionary * index in _investigateArray) {
  675. UIAlertAction * action = [UIAlertAction actionWithTitle:[index objectForKey:@"name"] style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
  676. [QMConnect sdkSubmitInvestigate:[index objectForKey:@"name"] value:[index objectForKey:@"value"] successBlock:^{
  677. NSLog(@"评价成功");
  678. } failBlock:^{
  679. NSLog(@"评价失败");
  680. }];
  681. }];
  682. [investigateAlertView addAction:action];
  683. }
  684. UIAlertAction * cancelAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"button.cancel", nil) style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
  685. }];
  686. [investigateAlertView addAction:cancelAction];
  687. [self presentViewController:investigateAlertView animated:YES completion:nil];
  688. }
  689. #pragma mark - Send Message
  690. // 发送文本
  691. - (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text {
  692. if ([text isEqual:@"\n"]) {
  693. if (![_chatInputView.inputView.text isEqualToString:@""]) {
  694. NSString *text = [_chatInputView.inputView.textStorage getRichString];
  695. [self sendText:text];
  696. _chatInputView.inputView.text = @"";
  697. return NO;
  698. }
  699. return NO;
  700. }
  701. return YES;
  702. }
  703. //发送表情
  704. - (void)sendBtnAction:(UIButton *)button {
  705. if (![_chatInputView.inputView.text isEqualToString:@""]) {
  706. NSString *text = [_chatInputView.inputView.textStorage getRichString];
  707. [self sendText:text];
  708. _chatInputView.inputView.text = @"";
  709. }
  710. }
  711. - (void)sendText:(NSString *)text {
  712. [QMConnect sendMsgText:text successBlock:^{
  713. NSLog(@"发送成功");
  714. dispatch_async(dispatch_get_main_queue(), ^{
  715. [self createNSTimer];
  716. });
  717. } failBlock:^(NSString *str) {
  718. NSLog(@"发送失败");
  719. }];
  720. }
  721. // 发送图片
  722. - (void)sendImage:(UIImage *)image {
  723. [QMConnect sendMsgPic:image successBlock:^{
  724. NSLog(@"图片发送成功");
  725. dispatch_async(dispatch_get_main_queue(), ^{
  726. [self createNSTimer];
  727. });
  728. } failBlock:^(NSString *str) {
  729. NSLog(@"图片发送失败");
  730. }];
  731. }
  732. // 发送语音
  733. - (void)sendAudio:(NSString *)fileName duration:(NSString *)duration {
  734. NSString *filePath = [NSString stringWithFormat:@"%@.mp3", fileName];
  735. [QMConnect sendMsgAudio:filePath duration:duration successBlock:^{
  736. NSLog(@"语音发送成功");
  737. dispatch_async(dispatch_get_main_queue(), ^{
  738. [self createNSTimer];
  739. });
  740. } failBlock:^(NSString *str) {
  741. NSLog(@"语音发送失败");
  742. }];
  743. }
  744. // 发送文件消息
  745. - (void)sendFileMessageWithName:(NSString *)fileName AndSize:(NSString *)fileSize AndPath:(NSString *)filePath {
  746. [QMConnect sendMsgFile:fileName filePath:filePath fileSize:fileSize progressHander:^(float progress) {
  747. dispatch_async(dispatch_get_main_queue(), ^{
  748. self.upProgress = progress;
  749. [self.chatTableView reloadData];
  750. });
  751. } successBlock:^{
  752. NSLog(@"文件上传成功");
  753. dispatch_async(dispatch_get_main_queue(), ^{
  754. [self createNSTimer];
  755. self.upProgress = 0;
  756. });
  757. } failBlock:^(NSString *str) {
  758. NSLog(@"文件上传失败");
  759. dispatch_async(dispatch_get_main_queue(), ^{
  760. self.upProgress = 0;
  761. });
  762. }];
  763. }
  764. // 失败消息重新发送
  765. - (void)resendAction:(QMTapGestureRecognizer *)gestureRecognizer {
  766. NSArray * dataArray = [[NSArray alloc] init];
  767. dataArray = [QMConnect getOneDataFromDatabase:gestureRecognizer.messageId];
  768. for (CustomMessage * custom in dataArray) {
  769. [QMConnect resendMessage:custom successBlock:^{
  770. NSLog(@"重新发送成功");
  771. dispatch_async(dispatch_get_main_queue(), ^{
  772. [self createNSTimer];
  773. });
  774. } failBlock:^(NSString *str) {
  775. NSLog(@"重新发送失败");
  776. }];
  777. }
  778. }
  779. // 表情代理及相关处理
  780. - (void)SendTheFaceStr:(NSString *)faceStr isDelete:(BOOL)dele {
  781. if (dele) {
  782. [_chatInputView.inputView deleteBackward];
  783. }else {
  784. [self insertEmoji:faceStr];
  785. }
  786. }
  787. - (void)insertEmoji: (NSString *)code {
  788. QMTextAttachment * emojiTextAttemt = [QMTextAttachment new];
  789. NSString *bundlePath = [[NSBundle mainBundle] pathForResource:@"QMEmoticon" ofType:@"bundle"];
  790. NSString *fileName = [[NSBundle mainBundle] pathForResource:@"expressionImage" ofType:@"plist"];
  791. NSDictionary *plistDict = [NSDictionary dictionaryWithContentsOfFile:fileName];
  792. if ([plistDict objectForKey:code] != nil) {
  793. emojiTextAttemt.emojiCode = code;
  794. emojiTextAttemt.image = [UIImage imageNamed:[NSString stringWithFormat:@"%@/%@", bundlePath, [plistDict objectForKey:code]]];
  795. emojiTextAttemt.bounds = CGRectMake(0, 0, 18, 18);
  796. NSAttributedString * attributeString = [NSAttributedString attributedStringWithAttachment:emojiTextAttemt];
  797. NSRange range = [_chatInputView.inputView selectedRange];
  798. if (range.length > 0) {
  799. [_chatInputView.inputView.textStorage deleteCharactersInRange:range];
  800. }
  801. [_chatInputView.inputView.textStorage insertAttributedString:attributeString atIndex:[_chatInputView.inputView selectedRange].location];
  802. _chatInputView.inputView.selectedRange = NSMakeRange(_chatInputView.inputView.selectedRange.location+1, 0);
  803. }
  804. [self resetTextStyle];
  805. }
  806. - (void)resetTextStyle {
  807. NSRange wholeRange = NSMakeRange(0, _chatInputView.inputView.textStorage.length);
  808. [_chatInputView.inputView.textStorage removeAttribute:NSFontAttributeName range:wholeRange];
  809. [_chatInputView.inputView.textStorage addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:18] range:wholeRange];
  810. _chatInputView.inputView.font = [UIFont systemFontOfSize:18];
  811. }
  812. // 机器人帮助评价
  813. - (void)sendRobotFeedback: (BOOL)isUseful questionId: (NSString *)questionId messageId: (NSString *)messageId robotType: (NSString *)robotType robotId: (NSString *)robotId robotMsgId: (NSString *)robotMsgId {
  814. __weak QMChatRoomViewController *weakSelf = self;
  815. [QMConnect sdkSubmitRobotFeedback:isUseful questionId:questionId messageId:messageId robotType:robotType robotId:robotId robotMsgId:robotMsgId successBlock:^{
  816. dispatch_async(dispatch_get_main_queue(), ^{
  817. [weakSelf getData];
  818. [weakSelf.chatTableView reloadData];
  819. });
  820. } failBlock:^{
  821. }];
  822. }
  823. #pragma mark - Multi Function
  824. // 注销事件
  825. - (void)logoutAction {
  826. [[QMAudioPlayer sharedInstance] stopAudioPlayer];
  827. [QMConnect logout];
  828. [self removeTimer];
  829. NSArray *viewcontrollers = self.navigationController.viewControllers;
  830. if (viewcontrollers.count>1) {
  831. if ([viewcontrollers objectAtIndex:viewcontrollers.count-1]==self) {
  832. //push方式
  833. [self.navigationController popViewControllerAnimated:YES];
  834. }
  835. }
  836. else{
  837. //present方式
  838. [self.navigationController dismissViewControllerAnimated:YES completion:^{
  839. [self cw_dismissViewController];
  840. }];
  841. }
  842. }
  843. // 转人工客服
  844. - (void)customClick {
  845. [QMConnect sdkConvertManual:^{
  846. NSLog(@"转人工客服成功");
  847. // [self insertCardInfoMessage];
  848. } failBlock:^{
  849. NSLog(@"转人工客服失败");
  850. dispatch_async(dispatch_get_main_queue(), ^{
  851. if (self.isOpenSchedule == false) {
  852. [self showGuestBookViewController];
  853. }
  854. });
  855. }];
  856. }
  857. #pragma mark - 留言提示
  858. - (void)showGuestBookViewController {
  859. [self.chatInputView setHidden:true];
  860. [self.manualButotn setHidden:true];
  861. self.chatTableView.frame = CGRectMake(0, 0, kScreenWidth, kScreenHeight - _navHeight);
  862. self.msg = [QMConnect leaveMessageAlert];
  863. if ([self.msg isEqualToString:@""]) {
  864. self.msg = NSLocalizedString(@"title.messageprompts", nil);
  865. }
  866. if ([QMConnect allowedLeaveMessage]) {
  867. UIAlertController *alertView = [UIAlertController alertControllerWithTitle:@"" message: self.msg preferredStyle:UIAlertControllerStyleAlert];
  868. UIAlertAction *sureAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"button.leaveMessage", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
  869. QMChatRoomGuestBookViewController *guestBookViewController = [[QMChatRoomGuestBookViewController alloc] init];
  870. guestBookViewController.peerId = self.peerId;
  871. [self.navigationController pushViewController:guestBookViewController animated:YES];
  872. }];
  873. UIAlertAction *cancel = [UIAlertAction actionWithTitle:NSLocalizedString(@"button.signOut", nil) style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
  874. [self logoutAction];
  875. }];
  876. [alertView addAction:sureAction];
  877. [alertView addAction:cancel];
  878. [self presentViewController:alertView animated:YES completion:nil];
  879. }else {
  880. UIAlertController *alertView = [UIAlertController alertControllerWithTitle:@"" message: self.msg preferredStyle:UIAlertControllerStyleAlert];
  881. UIAlertAction *cancel = [UIAlertAction actionWithTitle:NSLocalizedString(@"title.iknow", nil) style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
  882. }];
  883. [alertView addAction:cancel];
  884. [self presentViewController:alertView animated:YES completion:nil];
  885. }
  886. }
  887. #pragma mark - 客服代理方法
  888. /// 当前客服状态
  889. - (void)currentAgentStatus:(QMKStatus)status{
  890. switch (status) {
  891. case 0:
  892. _titleView.stateInfoLabel.text = NSLocalizedString(@"title.now_robit", nil);
  893. self.manualButotn.hidden = NO;
  894. break;
  895. case 1:
  896. _titleView.stateInfoLabel.text = NSLocalizedString(@"title.people_now", nil);
  897. self.manualButotn.hidden = YES;
  898. break;
  899. case 2:
  900. _titleView.stateInfoLabel.text = NSLocalizedString(@"title.people_isline", nil);
  901. self.manualButotn.hidden = NO;
  902. break;
  903. case 3:
  904. _titleView.stateInfoLabel.text = NSLocalizedString(@"title.people_now", nil);
  905. self.manualButotn.hidden = YES;
  906. break;
  907. case 4:
  908. _titleView.stateInfoLabel.text = NSLocalizedString(@"title.people_isleave", nil);
  909. self.manualButotn.hidden = YES;
  910. break;
  911. default:
  912. break;
  913. }
  914. }
  915. /// 当前坐席信息
  916. - (void)currentAgentInfoWithAgent:(QMAgent * _Nonnull)agent {
  917. NSString *string = [NSString stringWithFormat:@"%@(%@)", agent.name, agent.exten];
  918. string = [string stringByReplacingOccurrencesOfString:@"\n" withString:@""];
  919. _titleView.nameLabel.text = [NSString stringWithFormat:@"%@",string];
  920. }
  921. /// 当前会话排队数
  922. - (void)currentSessionWaitNumberWithNumber:(NSInteger)number {
  923. _titleView.stateInfoLabel.text = [NSString stringWithFormat:@"%@: %ld",NSLocalizedString(@"title.line_up", nil), (long)number];
  924. self.manualButotn.hidden = YES;
  925. }
  926. /// 邀请评价
  927. - (void)inviteEvaluate {
  928. UIAlertController * alertController = [UIAlertController alertControllerWithTitle:@"" message:NSLocalizedString(@"button.chat_evaluate", nil) preferredStyle:UIAlertControllerStyleActionSheet];
  929. for (NSDictionary *index in _investigateArray) {
  930. [alertController addAction:[UIAlertAction actionWithTitle:[index objectForKey:@"name"] style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
  931. [QMConnect sdkSubmitInvestigate:[index objectForKey:@"name"] value:[index objectForKey:@"value"] successBlock:^{
  932. NSLog(@"评价成功");
  933. } failBlock:^{
  934. NSLog(@"评价失败");
  935. }];
  936. }]];
  937. };
  938. [alertController addAction:[UIAlertAction actionWithTitle:NSLocalizedString(@"button.cancel", nil) style:UIAlertActionStyleDestructive handler:nil]];
  939. [self presentViewController:alertController animated:true completion:nil];
  940. }
  941. #pragma mark - Push Notification
  942. // 键盘通知
  943. - (void)keyboardFrameChange: (NSNotification *)notification {
  944. NSDictionary * userInfo = notification.userInfo;
  945. NSValue * value = [userInfo objectForKey:UIKeyboardFrameEndUserInfoKey];
  946. CGRect newFrame = [value CGRectValue];
  947. if (newFrame.origin.y == [UIScreen mainScreen].bounds.size.height) {
  948. [UIView animateWithDuration:0.3 animations:^{
  949. self.chatInputView.frame = CGRectMake(0, kScreenHeight-kInputViewHeight-_navHeight, kScreenWidth, kInputViewHeight);
  950. self.chatTableView.frame = CGRectMake(0, 0, kScreenWidth, kScreenHeight-_navHeight-kInputViewHeight);
  951. }];
  952. }else {
  953. [UIView animateWithDuration:0.3 animations:^{
  954. self.chatInputView.frame = CGRectMake(0, [UIScreen mainScreen].bounds.size.height-kInputViewHeight-newFrame.size.height-_navHeight, kScreenWidth, kInputViewHeight);
  955. self.chatTableView.frame = CGRectMake(0, 0, kScreenWidth, [UIScreen mainScreen].bounds.size.height-_navHeight-kInputViewHeight-newFrame.size.height);
  956. [self scrollToEnd];
  957. }];
  958. }
  959. }
  960. // 机器人客服
  961. - (void)robotAction {
  962. NSLog(@"机器人客服");
  963. _titleView.stateInfoLabel.text = NSLocalizedString(@"title.now_robit", nil);
  964. self.manualButotn.hidden = NO;
  965. self.isRobot = YES;
  966. }
  967. // 客服在线
  968. - (void)customOnline {
  969. NSLog(@"客服在线");
  970. _titleView.stateInfoLabel.text = NSLocalizedString(@"title.people_now", nil);
  971. self.manualButotn.hidden = YES;
  972. self.isRobot = NO;
  973. [self createNSTimer];
  974. }
  975. // 客服离线
  976. - (void)customOffline {
  977. NSLog(@"客服离线");
  978. self.manualButotn.hidden = NO;
  979. _titleView.stateInfoLabel.text = NSLocalizedString(@"title.people_isline", nil);
  980. [self showGuestBookViewController];
  981. }
  982. // 会话领取
  983. - (void)customClaim {
  984. NSLog(@"会话被坐席领取");
  985. _titleView.stateInfoLabel.text = NSLocalizedString(@"title.people_now", nil);
  986. self.manualButotn.hidden = YES;
  987. self.isRobot = NO;
  988. }
  989. // 离线推送 (坐席在后台结束会话,返回上一界面)
  990. - (void)customFinish {
  991. NSLog(@"客服结束会话");
  992. [self.chatInputView setHidden:true];
  993. self.manualButotn.hidden = YES;
  994. self.chatTableView.frame = CGRectMake(0, 0, kScreenWidth, kScreenHeight - _navHeight);
  995. _titleView.stateInfoLabel.text = NSLocalizedString(@"title.people_now", nil);
  996. }
  997. // 排队人数
  998. - (void)customQueue: (NSNotification *)notification {
  999. NSLog(@"排队人数 %@", notification.object);
  1000. _titleView.stateInfoLabel.text = [NSString stringWithFormat:@"%@: %@",NSLocalizedString(@"title.line_up", nil), notification.object];
  1001. self.manualButotn.hidden = YES;
  1002. }
  1003. // 满意度推送
  1004. - (void)customInvestigate {
  1005. NSLog(@"满意度通知");
  1006. UIAlertController * alertController = [UIAlertController alertControllerWithTitle:@"" message:NSLocalizedString(@"button.chat_evaluate", nil) preferredStyle:UIAlertControllerStyleActionSheet];
  1007. for (NSDictionary *index in _investigateArray) {
  1008. [alertController addAction:[UIAlertAction actionWithTitle:[index objectForKey:@"name"] style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
  1009. [QMConnect sdkSubmitInvestigate:[index objectForKey:@"name"] value:[index objectForKey:@"value"] successBlock:^{
  1010. NSLog(@"评价成功");
  1011. } failBlock:^{
  1012. NSLog(@"评价失败");
  1013. }];
  1014. }]];
  1015. };
  1016. [alertController addAction:[UIAlertAction actionWithTitle:NSLocalizedString(@"button.cancel", nil) style:UIAlertActionStyleDestructive handler:nil]];
  1017. [self presentViewController:alertController animated:true completion:nil];
  1018. }
  1019. // 坐席信息 (坐席工号、坐席名称、坐席头像) 可能为空字符串需要判断
  1020. - (void)customAgentMessage: (NSNotification *)notification {
  1021. QMAgent *agent = notification.object;
  1022. NSString *string;
  1023. if ([agent.type isEqualToString:@"robot"]) {
  1024. string = [NSString stringWithFormat:@"%@", agent.name];
  1025. }else if ([agent.type isEqualToString:@"activeClaim"]){
  1026. string = [NSString stringWithFormat:@"%@(%@)", agent.name, agent.exten];
  1027. [self customOnline];
  1028. }else {
  1029. string = [NSString stringWithFormat:@"%@(%@)", agent.name, agent.exten];
  1030. }
  1031. string = [string stringByReplacingOccurrencesOfString:@"\n" withString:@""];
  1032. _titleView.nameLabel.text = [NSString stringWithFormat:@"%@",string];
  1033. }
  1034. // 专属坐席不在线通知 调用接受其他坐席服务接口成功后调用 beginSession
  1035. - (void)customVIP {
  1036. [QMAlert showMessage:NSLocalizedString(@"title.schedule_notonline", nil)];
  1037. __weak QMChatRoomViewController * myChatView = self;
  1038. [QMConnect sdkAcceptOtherAgentWithPeer:self.peerId successBlock:^{
  1039. NSLog(@"成功");
  1040. [myChatView beginSession];
  1041. } failBlock:^{
  1042. NSLog(@"失败");
  1043. [QMAlert showMessage:NSLocalizedString(@"title.schedule_faile", nil)];
  1044. }];
  1045. }
  1046. #pragma mark - 日程管理的留言
  1047. - (void)customLeavemsg: (NSNotification*)notification {
  1048. NSArray *array = notification.object;
  1049. NSString *str = array[0];
  1050. [QMConnect sdkGetWebchatScheduleConfig:^(NSDictionary * _Nonnull scheduleDic) {
  1051. dispatch_async(dispatch_get_main_queue(), ^{
  1052. for (NSDictionary*dic in scheduleDic[@"leavemsgNodes"]) {
  1053. if ([str isEqualToString:dic[@"_id"]]){
  1054. self.LeaveArray = dic[@"leavemsgFields"];
  1055. QMChatRoomGuestBookViewController *guestBookViewController = [[QMChatRoomGuestBookViewController alloc] init];
  1056. guestBookViewController.peerId = array[1];
  1057. guestBookViewController.contactFields = self.LeaveArray;
  1058. guestBookViewController.leaveMsg = dic[@"contentTip"];
  1059. guestBookViewController.isScheduleLeave = true;
  1060. [self.navigationController pushViewController:guestBookViewController animated:YES];
  1061. }
  1062. }
  1063. });
  1064. } failBlock:^{
  1065. NSLog(@"日程管理进入留言失败");
  1066. }];
  1067. }
  1068. - (void)beginSession {
  1069. __weak QMChatRoomViewController * myChatView = self;
  1070. [QMConnect sdkBeginNewChatSession:self.peerId successBlock:^(BOOL remark, NSString *str) {
  1071. NSLog(@"开始会话成功");
  1072. dispatch_async(dispatch_get_main_queue(), ^{
  1073. // 是否启动了评价功能
  1074. if (remark == NO) {
  1075. myChatView.addView.evaluateBtn.hidden = YES;
  1076. myChatView.addView.evaluateLabel.hidden = YES;
  1077. }else {
  1078. myChatView.addView.evaluateBtn.hidden = NO;
  1079. myChatView.addView.evaluateLabel.hidden = NO;
  1080. }
  1081. });
  1082. } failBlock:^(NSString *str) {
  1083. NSLog(@"开始会话失败, %@" , str);
  1084. }];
  1085. }
  1086. // 坐席正在输入
  1087. - (void)changeCustomStatus {
  1088. if (![_titleView.stateInfoLabel.text isEqual: NSLocalizedString(@"title.other_writing", nil)]) {
  1089. NSString *str = _titleView.stateInfoLabel.text;
  1090. _titleViewText = str;
  1091. }
  1092. _titleView.stateInfoLabel.text = NSLocalizedString(@"title.other_writing", nil);
  1093. backStatus = nil;
  1094. backStatus = [NSTimer scheduledTimerWithTimeInterval:5 target:self selector:@selector(backCustomStatus:) userInfo:nil repeats:NO];
  1095. [[NSRunLoop mainRunLoop] addTimer:backStatus forMode:NSRunLoopCommonModes];
  1096. }
  1097. - (void)backCustomStatus:(NSTimer *)time{
  1098. _titleView.stateInfoLabel.text = _titleViewText;
  1099. [backStatus invalidate];
  1100. }
  1101. // 撤回消息
  1102. - (void)cbangeDrowMessageStatus: (NSNotification*)notification {
  1103. NSString *messageId = notification.object;
  1104. [QMConnect changeDrawMessageStatus:messageId];
  1105. [self getData];
  1106. [self reloadTableView];
  1107. }
  1108. // 访客无响应断开计时(开启无响应断开的需要把方法中的代码放开)
  1109. - (void)createNSTimer{
  1110. NSLog(@"开启无响应定时器");
  1111. // [self removeTimer];
  1112. // self.breakDuration = [QMConnect breakSessionDuration];
  1113. // self.breakTipsDuration = [QMConnect breakSessionAlertDuration];
  1114. // if (self.breakDuration && self.breakTipsDuration && [QMConnect allowedBreakSession]) {
  1115. // breakTipTimer = [NSTimer scheduledTimerWithTimeInterval:self.breakTipsDuration * 60 target:self selector:@selector(breakTipTimerAction:) userInfo:nil repeats:NO];
  1116. // breakTimer = [NSTimer scheduledTimerWithTimeInterval:self.breakDuration * 60 target:self selector:@selector(breakTimerAction:) userInfo:nil repeats:NO];
  1117. // [[NSRunLoop mainRunLoop] addTimer:breakTimer forMode:NSRunLoopCommonModes];
  1118. // [[NSRunLoop mainRunLoop] addTimer:breakTipTimer forMode:NSRunLoopCommonModes];
  1119. // }
  1120. }
  1121. - (void)removeTimer {
  1122. if (breakTipTimer) {
  1123. [breakTipTimer invalidate];
  1124. breakTipTimer = nil;
  1125. }
  1126. if (breakTimer) {
  1127. [breakTimer invalidate];
  1128. breakTimer = nil;
  1129. }
  1130. }
  1131. - (void)breakTimerAction:(NSTimer *)time{
  1132. [self.chatInputView setHidden:true];
  1133. [self.manualButotn setHidden:true];
  1134. self.chatTableView.frame = CGRectMake(0, 0, kScreenWidth, kScreenHeight - _navHeight);
  1135. }
  1136. - (void)breakTipTimerAction:(NSTimer *)timer{
  1137. [QMAlert showMessage:[QMConnect breakSessionAlert]];
  1138. [breakTipTimer invalidate];
  1139. }
  1140. - (void)didReceiveMemoryWarning {
  1141. [super didReceiveMemoryWarning];
  1142. // Dispose of any resources that can be recreated.
  1143. }
  1144. @end