ContactSearchViewController.swift 14 KB

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