JCSearchResultViewController.swift 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451
  1. //
  2. // JCSearchResultViewController.swift
  3. // JChat
  4. //
  5. // Created by deng on 2017/5/5.
  6. // Copyright © 2017年 HXHG. All rights reserved.
  7. //
  8. import UIKit
  9. class JCSearchResultViewController: UIViewController {
  10. var message: JMSGMessage?
  11. var fromUser: JMSGUser!
  12. weak var delegate: UIViewController?
  13. override func viewDidLoad() {
  14. super.viewDidLoad()
  15. _init()
  16. }
  17. override func viewDidAppear(_ animated: Bool) {
  18. super.viewDidAppear(animated)
  19. navigationController?.isNavigationBarHidden = true
  20. if searchController != nil {
  21. searchController.searchBar.isHidden = false
  22. }
  23. }
  24. override func viewWillDisappear(_ animated: Bool) {
  25. super.viewWillAppear(animated)
  26. navigationController?.isNavigationBarHidden = false
  27. }
  28. deinit {
  29. NotificationCenter.default.removeObserver(self)
  30. }
  31. var searchController: UISearchController!
  32. fileprivate lazy var tableView: UITableView = {
  33. var tableView = UITableView(frame: .zero, style: .grouped)
  34. tableView.keyboardDismissMode = .onDrag
  35. tableView.delegate = self
  36. tableView.dataSource = self
  37. tableView.sectionIndexBackgroundColor = .clear
  38. tableView.register(JCContacterCell.self, forCellReuseIdentifier: "JCContacterCell")
  39. tableView.frame = CGRect(x: 0, y: 64, width: self.view.width, height: self.view.height - 64)
  40. return tableView
  41. }()
  42. fileprivate lazy var tagArray = ["联系人", "群组"]
  43. fileprivate lazy var users: [JMSGUser] = []
  44. fileprivate lazy var groups: [JMSGGroup] = []
  45. dynamic lazy var filteredUsersArray: [JMSGUser] = []
  46. dynamic lazy var filteredGroupsArray: [JMSGGroup] = []
  47. fileprivate var searchString = ""
  48. private lazy var tipsLabel: UILabel = UILabel(frame: CGRect(x: 0, y: 100, width: self.view.width, height: 22.5))
  49. private lazy var networkErrorView: UIView = {
  50. let tipsView = UIView(frame: CGRect(x: 0, y: 64, width: self.view.width, height: self.view.height))
  51. var tipsLabel: UILabel = UILabel(frame: CGRect(x: 0, y: 100, width: tipsView.width, height: 22.5))
  52. tipsLabel.textColor = UIColor(netHex: 0x999999)
  53. tipsLabel.textAlignment = .center
  54. tipsLabel.font = UIFont.systemFont(ofSize: 16)
  55. tipsLabel.text = "无法连接网络"
  56. tipsView.addSubview(tipsLabel)
  57. tipsView.isHidden = true
  58. tipsView.backgroundColor = .white
  59. return tipsView
  60. }()
  61. fileprivate var selectGroup: JMSGGroup!
  62. fileprivate var selectUser: JMSGUser!
  63. private func _init() {
  64. view.backgroundColor = UIColor(netHex: 0xe8edf3)
  65. automaticallyAdjustsScrollViewInsets = false
  66. navigationController?.automaticallyAdjustsScrollViewInsets = false
  67. tipsLabel.font = UIFont.systemFont(ofSize: 16)
  68. tipsLabel.textColor = UIColor(netHex: 0x999999)
  69. tipsLabel.textAlignment = .center
  70. view.addSubview(tipsLabel)
  71. _getDate()
  72. view.addSubview(tableView)
  73. view.addSubview(networkErrorView)
  74. if JCNetworkManager.isNotReachable {
  75. networkErrorView.isHidden = false
  76. }
  77. NotificationCenter.default.addObserver(self, selector: #selector(reachabilityChanged(note:)), name: NSNotification.Name(rawValue: "kNetworkReachabilityChangedNotification"), object: nil)
  78. }
  79. func reachabilityChanged(note: NSNotification) {
  80. if let curReach = note.object as? Reachability {
  81. let status = curReach.currentReachabilityStatus()
  82. switch status {
  83. case NotReachable:
  84. networkErrorView.isHidden = false
  85. default :
  86. networkErrorView.isHidden = true
  87. }
  88. }
  89. }
  90. private func _getDate() {
  91. users.removeAll()
  92. groups.removeAll()
  93. JMSGConversation.allConversations { (result, error) in
  94. if error == nil {
  95. if let conversations = result as? [JMSGConversation] {
  96. for conv in conversations {
  97. if !conv.ex.isGroup {
  98. let user = conv.target as! JMSGUser
  99. self.users.append(user)
  100. }
  101. }
  102. if !self.searchString.isEmpty {
  103. self.filter(self.searchString)
  104. }
  105. }
  106. }
  107. JMSGFriendManager.getFriendList { (result, error) in
  108. if error == nil {
  109. let users = result as! [JMSGUser]
  110. for user in users {
  111. if !self.users.contains(user) {
  112. self.users.append(user)
  113. }
  114. }
  115. if !self.searchString.isEmpty {
  116. self.filter(self.searchString)
  117. }
  118. }
  119. }
  120. JMSGGroup.myGroupArray { (result, error) in
  121. if error != nil {
  122. return
  123. }
  124. for item in result as! [NSNumber] {
  125. JMSGGroup.groupInfo(withGroupId: "\(item)", completionHandler: { (result, error) in
  126. guard let group = result as? JMSGGroup else {
  127. return
  128. }
  129. self.groups.append(group)
  130. if !self.searchString.isEmpty {
  131. self.filter(self.searchString)
  132. }
  133. })
  134. }
  135. }
  136. }
  137. }
  138. fileprivate func filter(_ searchString: String) {
  139. if searchString.isEmpty || searchString == "" {
  140. return
  141. }
  142. filteredUsersArray = _JCFilterUsers(users: users, string: searchString)
  143. filteredGroupsArray = _JCFilterGroups(groups: groups, string: searchString)
  144. if filteredUsersArray.count == 0 && filteredGroupsArray.count == 0 {
  145. tableView.isHidden = true
  146. let attr = NSMutableAttributedString(string: "没有搜到 ")
  147. let attrSearchString = NSAttributedString(string: searchString, attributes: [ NSAttributedString.Key.foregroundColor : O2ThemeManager.color(for: "Base.base_color")!, NSAttributedString.Key.font : UIFont.boldSystemFont(ofSize: 16.0)])
  148. attr.append(attrSearchString)
  149. attr.append(NSAttributedString(string: " 相关的信息"))
  150. tipsLabel.attributedText = attr
  151. return
  152. } else {
  153. tableView.isHidden = false
  154. }
  155. tableView.reloadData()
  156. }
  157. fileprivate func sendBusinessCard() {
  158. JCAlertView.bulid().setTitle("发送给:\(selectGroup.displayName())")
  159. .setMessage(fromUser!.displayName() + "的名片")
  160. .setDelegate(self)
  161. .addCancelButton("取消")
  162. .addButton("确定")
  163. .setTag(10003)
  164. .show()
  165. }
  166. fileprivate func forwardMessage(_ message: JMSGMessage) {
  167. let alertView = JCAlertView.bulid().setJMessage(message)
  168. .setDelegate(self)
  169. .setTag(10001)
  170. if selectUser == nil {
  171. alertView.setTitle("发送给:\(selectGroup.displayName())")
  172. } else {
  173. alertView.setTitle("发送给:\(selectUser.displayName())")
  174. }
  175. alertView.show()
  176. }
  177. public func close() {
  178. searchController.isActive = false
  179. delegate?.dismiss(animated: true, completion: nil)
  180. }
  181. }
  182. extension JCSearchResultViewController: UIAlertViewDelegate {
  183. func alertView(_ alertView: UIAlertView, clickedButtonAt buttonIndex: Int) {
  184. if buttonIndex != 1 {
  185. return
  186. }
  187. switch alertView.tag {
  188. case 10001:
  189. if selectUser != nil {
  190. JMSGMessage.forwardMessage(message!, target: selectUser, optionalContent: JMSGOptionalContent.ex.default)
  191. } else {
  192. JMSGMessage.forwardMessage(message!, target: selectGroup, optionalContent: JMSGOptionalContent.ex.default)
  193. }
  194. case 10003:
  195. if selectUser != nil {
  196. JMSGConversation.createSingleConversation(withUsername: selectUser.username) { (result, error) in
  197. if let conversation = result as? JMSGConversation {
  198. let message = JMSGMessage.ex.createBusinessCardMessage(conversation, self.fromUser.username, self.fromUser.appKey ?? "")
  199. JMSGMessage.send(message, optionalContent: JMSGOptionalContent.ex.default)
  200. }
  201. }
  202. } else {
  203. let msg = JMSGMessage.ex.createBusinessCardMessage(gid: selectGroup.gid, userName: fromUser!.username, appKey: fromUser!.appKey ?? "")
  204. JMSGMessage.send(msg, optionalContent: JMSGOptionalContent.ex.default)
  205. }
  206. default:
  207. break
  208. }
  209. MBProgressHUD_JChat.show(text: "已发送", view: view, 2)
  210. let time: TimeInterval = 2
  211. DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.1) {
  212. NotificationCenter.default.post(name: NSNotification.Name(rawValue: kReloadAllMessage), object: nil)
  213. }
  214. DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + time) { [weak self] in
  215. self?.close()
  216. }
  217. }
  218. }
  219. //Mark: -
  220. extension JCSearchResultViewController: UITableViewDelegate, UITableViewDataSource {
  221. func numberOfSections(in tableView: UITableView) -> Int {
  222. if filteredUsersArray.count > 0 && filteredGroupsArray.count > 0 {
  223. return 2
  224. }
  225. if filteredUsersArray.count == 0 && filteredGroupsArray.count == 0 {
  226. return 0
  227. }
  228. return 1
  229. }
  230. public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
  231. let userCount = filteredUsersArray.count > 3 ? 4 : filteredUsersArray.count
  232. let groupCount = filteredGroupsArray.count > 3 ? 4 : filteredGroupsArray.count
  233. if section == 0 && userCount > 0 {
  234. return userCount
  235. } else if groupCount > 0 {
  236. return groupCount
  237. }
  238. if userCount > 0 && groupCount > 0 {
  239. if section == 0 {
  240. return userCount
  241. } else {
  242. return groupCount
  243. }
  244. }
  245. return 0
  246. }
  247. func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
  248. if filteredUsersArray.count <= 0 {
  249. return tagArray.last
  250. }
  251. return tagArray[section]
  252. }
  253. func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
  254. if indexPath.row == 3 {
  255. return 40
  256. }
  257. return 55
  258. }
  259. func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
  260. return 35
  261. }
  262. func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
  263. return 0.001
  264. }
  265. func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
  266. if indexPath.row == 3 {
  267. var cell = tableView.dequeueReusableCell(withIdentifier: "JCMoreCell")
  268. if cell == nil {
  269. cell = UITableViewCell(style: .value2, reuseIdentifier: "JCMoreCell")
  270. }
  271. return cell!
  272. }
  273. return tableView.dequeueReusableCell(withIdentifier: "JCContacterCell", for: indexPath)
  274. }
  275. func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
  276. var isUser = false
  277. if indexPath.section == 0 && filteredUsersArray.count > 0 {
  278. isUser = true
  279. }
  280. if indexPath.row == 3 {
  281. cell.detailTextLabel?.text = isUser ? "查看更多联系人" : "查看更多群组"
  282. cell.detailTextLabel?.textColor = UIColor(netHex: 0x999999)
  283. cell.accessoryType = .disclosureIndicator
  284. return
  285. }
  286. guard let cell = cell as? JCContacterCell else {
  287. return
  288. }
  289. if isUser {
  290. cell.bindDate(filteredUsersArray[indexPath.row])
  291. } else {
  292. cell.bindDateWithGroup(group: filteredGroupsArray[indexPath.row])
  293. }
  294. }
  295. func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
  296. tableView.deselectRow(at: indexPath, animated: true)
  297. var isUser = false
  298. if indexPath.section == 0 && filteredUsersArray.count > 0 {
  299. isUser = true
  300. }
  301. if indexPath.row == 3 {
  302. let vc = JCMoreResultViewController()
  303. vc.fromUser = fromUser
  304. vc.message = message
  305. vc.delegate = self
  306. if isUser {
  307. vc.users = filteredUsersArray
  308. } else {
  309. vc.groups = filteredGroupsArray
  310. }
  311. vc.searchResultView = self
  312. vc.searchController = self.searchController
  313. if searchController != nil {
  314. searchController.searchBar.resignFirstResponder()
  315. }
  316. navigationController?.pushViewController(vc, animated: true)
  317. return
  318. }
  319. if isUser {
  320. let user = filteredUsersArray[indexPath.row]
  321. selectUser = user
  322. if let message = message {
  323. forwardMessage(message)
  324. return
  325. }
  326. if fromUser != nil {
  327. sendBusinessCard()
  328. return
  329. }
  330. let vc = JCUserInfoViewController()
  331. vc.user = user
  332. if searchController != nil {
  333. searchController.searchBar.resignFirstResponder()
  334. searchController.searchBar.isHidden = true
  335. }
  336. navigationController?.pushViewController(vc, animated: true)
  337. } else {
  338. let group = filteredGroupsArray[indexPath.row]
  339. selectGroup = group
  340. if let message = self.message {
  341. forwardMessage(message)
  342. return
  343. }
  344. if self.fromUser != nil {
  345. sendBusinessCard()
  346. return
  347. }
  348. JMSGConversation.createGroupConversation(withGroupId: group.gid) { (result, error) in
  349. let conv = result as! JMSGConversation
  350. let vc = JCChatViewController(conversation: conv)
  351. NotificationCenter.default.post(name: NSNotification.Name(rawValue: kUpdateConversation), object: nil, userInfo: nil)
  352. if self.searchController != nil {
  353. self.searchController.searchBar.resignFirstResponder()
  354. self.searchController.searchBar.isHidden = true
  355. }
  356. self.navigationController?.pushViewController(vc, animated: true)
  357. }
  358. }
  359. }
  360. }
  361. extension JCSearchResultViewController: UISearchResultsUpdating {
  362. func updateSearchResults(for searchController: UISearchController) {
  363. self.searchController = searchController
  364. searchString = searchController.searchBar.text!
  365. filter(searchString)
  366. }
  367. }
  368. @inline(__always)
  369. internal func _JCFilterUsers(users: [JMSGUser], string: String) -> [JMSGUser] {
  370. let filteredUsersArray = users.filter( { (user: JMSGUser) -> Bool in
  371. let str = string.uppercased()
  372. let notename = user.noteName?.uppercased().contains(str) ?? false
  373. let nickname = user.nickname?.uppercased().contains(str) ?? false
  374. let username = user.username.uppercased().contains(str)
  375. if notename || nickname || username {
  376. return true
  377. } else {
  378. return false
  379. }
  380. })
  381. return filteredUsersArray
  382. }
  383. @inline(__always)
  384. internal func _JCFilterGroups(groups: [JMSGGroup], string: String) -> [JMSGGroup] {
  385. let filteredGroupsArray = groups.filter( { (group: JMSGGroup) -> Bool in
  386. let str = string.uppercased()
  387. if group.name?.uppercased().contains(str) ?? false ||
  388. group.gid.uppercased().contains(str) {
  389. return true
  390. } else {
  391. return false
  392. }
  393. })
  394. return filteredGroupsArray
  395. }