ContactSearchViewController.swift 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328
  1. //
  2. // ContactSearchViewController.swift
  3. // O2Platform
  4. //
  5. // Created by 刘振兴 on 16/7/18.
  6. // Copyright © 2016年 zoneland. All rights reserved.
  7. //
  8. import UIKit
  9. import Alamofire
  10. import AlamofireImage
  11. import AlamofireObjectMapper
  12. import SwiftyJSON
  13. import ObjectMapper
  14. import CocoaLumberjack
  15. class ContactSearchViewController: UITableViewController {
  16. var searchContacts:[Int:[CellViewModel]] = [:]
  17. var sections:[Int:String] = [:]
  18. let searchController = UISearchController(searchResultsController: nil)
  19. override func viewWillAppear(_ animated: Bool) {
  20. //self.navigationController?.navigationBarHidden = true
  21. //searchController.searchBar.showsCancelButton = false
  22. }
  23. override func viewDidDisappear(_ animated: Bool) {
  24. //self.navigationController?.navigationBarHidden = false
  25. }
  26. override func viewDidLoad() {
  27. super.viewDidLoad()
  28. self.title = "搜索"
  29. // if (self.navigationController != nil) {
  30. // self.navigationController?.navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .Cancel, target: self, action: #selector(closeSearch))
  31. // }
  32. searchController.delegate = self
  33. searchController.searchResultsUpdater = self
  34. searchController.searchBar.delegate = self
  35. searchBarInit(searchController.searchBar)
  36. searchController.searchBar.scopeButtonTitles = ["所有", "公司", "部门", "个人"]
  37. //searchController.searchBar.showsScopeBar = true
  38. self.definesPresentationContext = true
  39. searchController.dimsBackgroundDuringPresentation = false
  40. searchController.hidesNavigationBarDuringPresentation = false
  41. // Setup the Scope Bar
  42. //self.view.backgroundColor = RGB(251, g: 71, b: 71)
  43. tableView.tableHeaderView = searchController.searchBar
  44. tableView.tableHeaderView?.sizeToFit()
  45. //searchController.active = true
  46. //self.navigationController?.navigationBar.addSubview(searchController.searchBar)
  47. }
  48. private func searchBarInit(_ searchBar:UISearchBar){
  49. // searchBar.setBackgroundImage(UIImage(), for: .any, barMetrics: .default)
  50. // searchBar.barTintColor = navbar_barTint_color
  51. //
  52. if let searchField = searchBar.value(forKey: "searchField") as? UITextField {
  53. searchField.placeholder = "请输入搜索关键字"
  54. // searchField.backgroundColor = navbar_barTint_color
  55. // searchField.layer.cornerRadius = 14
  56. // searchField.layer.borderColor = UIColor.gray.cgColor
  57. // searchField.layer.borderWidth = 1
  58. // searchField.layer.masksToBounds = true
  59. }
  60. UIBarButtonItem.appearance(whenContainedInInstancesOf: [UISearchBar.self]).title = "取消"
  61. }
  62. override func didReceiveMemoryWarning() {
  63. super.didReceiveMemoryWarning()
  64. // Dispose of any resources that can be recreated.
  65. }
  66. // MARK: - Table view data source
  67. override func numberOfSections(in tableView: UITableView) -> Int {
  68. return self.searchContacts.count
  69. }
  70. override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
  71. return (self.searchContacts[section]?.count)!
  72. }
  73. override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
  74. let cell = tableView.dequeueReusableCell(withIdentifier: "searchItemCell", for: indexPath) as! ContactItemCell
  75. cell.cellViewModel = self.searchContacts[(indexPath as NSIndexPath).section]![(indexPath as NSIndexPath).row]
  76. return cell
  77. }
  78. override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
  79. return self.sections[section]
  80. }
  81. override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
  82. let cellViewModel = self.searchContacts[(indexPath as NSIndexPath).section]![(indexPath as NSIndexPath).row]
  83. switch cellViewModel.dataType {
  84. case .company(let c):
  85. //self.performSegueWithIdentifier("searchCompanyDepartSegue", sender: c)
  86. let contactStoryboard = UIStoryboard(name: "contacts", bundle: Bundle.main)
  87. let destVC = contactStoryboard.instantiateViewController(withIdentifier: "companyDept") as! ContactCompanyDeptController
  88. destVC.superCompany = c as? Company
  89. self.navigationController?.pushViewController(destVC, animated: true)
  90. case .depart(let d):
  91. let contactStoryboard = UIStoryboard(name: "contacts", bundle: Bundle.main)
  92. let destVC = contactStoryboard.instantiateViewController(withIdentifier: "DeptPerson") as! ContactDeptPersonController
  93. destVC.superOrgUnit = d as? OrgUnit
  94. self.navigationController?.pushViewController(destVC, animated: true)
  95. //self.performSegueWithIdentifier("searchDepartPersonSegue", sender: d)
  96. case .group(let g):
  97. self.performSegue(withIdentifier: "searchPersonGroupSegue", sender: g)
  98. case .identity(let i):
  99. self.performSegue(withIdentifier: "searchPersonInfoSegue", sender: i)
  100. case .person(let p):
  101. self.performSegue(withIdentifier: "searchPersonDetailInfoSegue", sender: p)
  102. case .title:
  103. break
  104. }
  105. }
  106. override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
  107. if segue.identifier == "searchCompanyDepartSegue" {
  108. let destVC = segue.destination as! ContactCompanyDeptController
  109. destVC.superCompany = sender as? Company
  110. }else if segue.identifier == "searchDepartPersonSegue" {
  111. let destVC = segue.destination as! ContactDeptPersonController
  112. destVC.superOrgUnit = sender as? OrgUnit
  113. }else if segue.identifier == "searchPersonDetailInfoSegue" {
  114. let destVC = segue.destination as! ContactPersonInfoController
  115. destVC.contact = sender as? PersonV2
  116. }
  117. }
  118. func loadSearchData(_ searchText:String?,scopeIndex:Int){
  119. //let sText = (searchText == nil ? "":searchText)
  120. //DDLogDebug("searchText=\(sText),scopeIndex = \(scopeIndex)")
  121. self.searchContacts.removeAll()
  122. if !(searchText?.isEmpty)! {
  123. let urls = getURLSFromScope(searchText!, scope: scopeIndex)
  124. if urls.count>1 {
  125. for (index,url) in urls {
  126. Alamofire.request(url).responseJSON {
  127. response in
  128. switch response.result {
  129. case .success(let val):
  130. let objects = JSON(val)["data"]
  131. self.searchContacts[index]?.removeAll()
  132. switch index {
  133. case 0:
  134. let companys = Mapper<Company>().mapArray(JSONString:objects.description)
  135. for comp in companys!{
  136. let vm = CellViewModel(name: comp.name,sourceObject: comp)
  137. self.searchContacts[index]?.append(vm)
  138. }
  139. case 1:
  140. let departmets = Mapper<Department>().mapArray(JSONString:objects.description)
  141. for dept in departmets!{
  142. let vm = CellViewModel(name: dept.name,sourceObject: dept)
  143. self.searchContacts[index]?.append(vm)
  144. }
  145. case 2:
  146. let persons = Mapper<Person>().mapArray(JSONString:objects.description)
  147. for person in persons!{
  148. let vm = CellViewModel(name: person.name,sourceObject: person)
  149. self.searchContacts[index]?.append(vm)
  150. }
  151. default:
  152. DDLogError("have no match category")
  153. }
  154. case .failure(let err):
  155. DDLogError("request err = \(err)")
  156. }
  157. self.tableView.reloadData()
  158. }
  159. }
  160. }else{
  161. let (index,url) = urls.first!
  162. Alamofire.request(url).responseJSON {
  163. response in
  164. switch response.result {
  165. case .success(let val):
  166. let objects = JSON(val)["data"]
  167. self.searchContacts[0]?.removeAll()
  168. switch index {
  169. case 0:
  170. let companys = Mapper<Company>().mapArray(JSONString:objects.description)
  171. for comp in companys!{
  172. let vm = CellViewModel(name: comp.name,sourceObject: comp)
  173. self.searchContacts[0]?.append(vm)
  174. }
  175. case 1:
  176. let departmets = Mapper<Department>().mapArray(JSONString:objects.description)
  177. for dept in departmets!{
  178. let vm = CellViewModel(name: dept.name,sourceObject: dept)
  179. self.searchContacts[0]?.append(vm)
  180. }
  181. case 2:
  182. let persons = Mapper<Person>().mapArray(JSONString:objects.description)
  183. for person in persons!{
  184. let vm = CellViewModel(name: person.name,sourceObject: person)
  185. self.searchContacts[0]?.append(vm)
  186. }
  187. default:
  188. DDLogError("have no match category")
  189. }
  190. case .failure(let err):
  191. DDLogError("request err = \(err)")
  192. }
  193. self.tableView.reloadData()
  194. }
  195. }
  196. }else{
  197. self.searchContacts.removeAll()
  198. self.sections.removeAll()
  199. self.tableView.reloadData()
  200. }
  201. //self.tableView.reloadData()
  202. }
  203. func getURLSFromScope(_ searchText:String,scope:Int)->[Int:String]{
  204. var urls:[Int:String]=[:]
  205. self.searchContacts.removeAll()
  206. switch scope {
  207. case 1:
  208. self.searchContacts = [0:[]]
  209. self.sections = [0:"公司列表"]
  210. let url = AppDelegate.o2Collect.generateURLWithAppContextKey(ContactContext.contactsContextKey, query: ContactContext.companySearchByKeyQuery, parameter: ["##key##":searchText as AnyObject])
  211. urls = [0:url!]
  212. case 2:
  213. self.searchContacts = [0:[]]
  214. self.sections = [0:"部门列表"]
  215. let url = AppDelegate.o2Collect.generateURLWithAppContextKey(ContactContext.contactsContextKey, query: ContactContext.departmentSearchByKeyQuery, parameter: ["##key##":searchText as AnyObject])
  216. urls = [1:url!]
  217. case 3:
  218. self.searchContacts = [0:[]]
  219. self.sections = [0:"人员列表"]
  220. let url = AppDelegate.o2Collect.generateURLWithAppContextKey(ContactContext.contactsContextKey, query: ContactContext.personSearchByKeyQuery, parameter: ["##key##":searchText as AnyObject])
  221. urls = [2:url!]
  222. default:
  223. self.searchContacts = [0:[],1:[],2:[]]
  224. self.sections = [0:"公司列表",1:"部门列表",2:"人员列表"]
  225. let url1 = AppDelegate.o2Collect.generateURLWithAppContextKey(ContactContext.contactsContextKey, query: ContactContext.companySearchByKeyQuery, parameter: ["##key##":searchText as AnyObject])
  226. let url2 = AppDelegate.o2Collect.generateURLWithAppContextKey(ContactContext.contactsContextKey, query: ContactContext.departmentSearchByKeyQuery, parameter: ["##key##":searchText as AnyObject])
  227. let url3 = AppDelegate.o2Collect.generateURLWithAppContextKey(ContactContext.contactsContextKey, query: ContactContext.personSearchByKeyQuery, parameter: ["##key##":searchText as AnyObject])
  228. urls[0]=url1!
  229. urls[1]=url2!
  230. urls[2]=url3!
  231. }
  232. return urls
  233. }
  234. @IBAction func closeWindow(_ sender: AnyObject) {
  235. if let preVC = self.presentedViewController {
  236. preVC.dismiss(animated: true, completion: {
  237. })
  238. }
  239. self.dismiss(animated: true, completion: nil)
  240. }
  241. // func closeSearch(sender:AnyObject?){
  242. // self.dismissViewControllerAnimated(true, completion: nil)
  243. // }
  244. }
  245. extension ContactSearchViewController:UISearchControllerDelegate{
  246. func willPresentSearchController(_ searchController: UISearchController) {
  247. NSLog("willPresentSearchController")
  248. }
  249. func didPresentSearchController(_ searchController: UISearchController) {
  250. NSLog("didPresentSearchController")
  251. searchController.searchBar.setShowsCancelButton(false, animated: true)
  252. }
  253. func willDismissSearchController(_ searchController: UISearchController) {
  254. NSLog("willDismissSearchController")
  255. }
  256. func didDismissSearchController(_ searchController: UISearchController) {
  257. NSLog("didDismissSearchController")
  258. }
  259. func presentSearchController(_ searchController: UISearchController) {
  260. NSLog("presentSearchController")
  261. }
  262. }
  263. extension ContactSearchViewController:UISearchBarDelegate{
  264. // func searchBarCancelButtonClicked(searchBar: UISearchBar) {
  265. // self.dismissViewControllerAnimated(true, completion: nil)
  266. // }
  267. func searchBar(_ searchBar: UISearchBar, selectedScopeButtonIndexDidChange selectedScope: Int) {
  268. self.loadSearchData(searchBar.text, scopeIndex: selectedScope)
  269. }
  270. }
  271. extension ContactSearchViewController:UISearchResultsUpdating{
  272. func updateSearchResults(for searchController: UISearchController) {
  273. let searchBar = searchController.searchBar
  274. self.loadSearchData(searchBar.text, scopeIndex: searchBar.selectedScopeButtonIndex)
  275. }
  276. }