ContactHomeViewController.swift 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397
  1. //
  2. // ContactHomeViewController.swift
  3. // O2Platform
  4. //
  5. // Created by 刘振兴 on 16/7/12.
  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. import O2OA_Auth_SDK
  16. class ContactHomeViewController: UITableViewController {
  17. var contacts:[Int:[CellViewModel]] = [0:[],1:[],2:[]]
  18. var myDepartmentURL:String? {
  19. let acc = O2AuthSDK.shared.myInfo()!
  20. let url = AppDelegate.o2Collect.generateURLWithAppContextKey(ContactContext.contactsContextKeyV2, query: ContactContext.personInfoByNameQuery, parameter: ["##name##":acc.unique! as AnyObject])
  21. return url
  22. }
  23. var myCompanyURL:String? {
  24. let url = AppDelegate.o2Collect.generateURLWithAppContextKey(ContactContext.contactsContextKeyV2, query: ContactContext.topUnitQuery, parameter:nil)
  25. return url
  26. }
  27. let searchUrl = AppDelegate.o2Collect.generateURLWithAppContextKey(ContactContext.contactsContextKeyV2, query: ContactContext.personSearchByKeyQueryV2, parameter: nil)
  28. var searchController : UISearchController!
  29. var searchResult : [CellViewModel] = []
  30. var searchFilter : String = ""
  31. override func viewDidLoad() {
  32. super.viewDidLoad()
  33. //let rightItem = UIBarButtonItem(image: UIImage(named: "contact_search"), style: .plain, target: self, action:#selector(ContactHomeViewController.rightItemAction(_:)))
  34. //self.navigationItem.rightBarButtonItem = rightItem
  35. self.tableView.mj_header = MJRefreshNormalHeader(refreshingTarget: self, refreshingAction: #selector(ContactHomeViewController.loadMyData(_:)))
  36. self.initSearch()
  37. self.definesPresentationContext = true
  38. self.automaticallyAdjustsScrollViewInsets = false
  39. self.loadMyData(nil)
  40. }
  41. override func viewWillAppear(_ animated: Bool) {
  42. super.viewWillAppear(animated)
  43. }
  44. override func viewWillDisappear(_ animated: Bool) {
  45. super.viewWillDisappear(animated)
  46. }
  47. private func initSearch(){
  48. searchController = UISearchController(searchResultsController: nil)
  49. searchController.delegate = self
  50. searchController.searchBar.delegate = self
  51. searchController.searchResultsUpdater = self
  52. searchController.dimsBackgroundDuringPresentation = false
  53. //searchController.hidesNavigationBarDuringPresentation = false
  54. UIBarButtonItem.appearance(whenContainedInInstancesOf: [UISearchBar.self]).title = "取消"
  55. let textFont = UIFont(name: "PingFangTC-Light", size: 14.0)
  56. let attrs = [NSAttributedString.Key.font: textFont!]
  57. UIBarButtonItem.appearance(whenContainedInInstancesOf: [UISearchBar.self]).setTitleTextAttributes(attrs, for: .normal)
  58. searchController.searchBar.searchBarStyle = UISearchBar.Style.minimal
  59. searchController.searchBar.sizeToFit()
  60. searchController.searchBar.placeholder = "请输入姓名、工号或拼音搜索..."
  61. self.tableView.tableHeaderView = searchController.searchBar
  62. }
  63. private func isSearchRealActive() -> Bool {
  64. return self.searchController.isActive && self.searchFilter != ""
  65. }
  66. override func didReceiveMemoryWarning() {
  67. super.didReceiveMemoryWarning()
  68. // Dispose of any resources that can be recreated.
  69. }
  70. // override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
  71. // if section == 0 {
  72. // return self.searchController.searchBar
  73. // }else{
  74. // return nil
  75. // }
  76. // }
  77. //
  78. // override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
  79. // if section == 0 {
  80. // return 48
  81. // }else{
  82. // return 18
  83. // }
  84. // }
  85. override func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
  86. return 0.1
  87. }
  88. override func numberOfSections(in tableView: UITableView) -> Int {
  89. // #warning Incomplete implementation, return the number of sections
  90. return self.isSearchRealActive() ? 1 : (contacts.count)
  91. }
  92. override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
  93. // #warning Incomplete implementation, return the number of rows
  94. return self.isSearchRealActive() ? self.searchResult.count : (contacts[section]?.count)!
  95. }
  96. override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
  97. let cellName = isSearchRealActive() ? "contactPersonCell" : "contactItemCell"
  98. let cell = tableView.dequeueReusableCell(withIdentifier: cellName, for: indexPath) as! ContactItemCell
  99. if isSearchRealActive() {
  100. cell.cellViewModel = self.searchResult[indexPath.row]
  101. } else {
  102. let cellMod = self.contacts[indexPath.section]![indexPath.row]
  103. if !cellMod.openFlag {
  104. cell.accessoryType = UITableViewCell.AccessoryType.none
  105. }else {
  106. cell.accessoryType = UITableViewCell.AccessoryType.disclosureIndicator
  107. }
  108. cell.cellViewModel = cellMod
  109. }
  110. return cell
  111. }
  112. /*override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
  113. switch section {
  114. case 0:
  115. return "我的部门"
  116. case 1:
  117. return "我的公司"
  118. case 2:
  119. return "常用联系人"
  120. default:
  121. return ""
  122. }
  123. }*/
  124. override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
  125. self.tableView.deselectRow(at: indexPath, animated: false)
  126. let cellViewModel = isSearchRealActive() ? self.searchResult[indexPath.row] : self.contacts[indexPath.section]![indexPath.row]
  127. switch cellViewModel.dataType {
  128. case .company(let c):
  129. self.performSegue(withIdentifier: "showDepartPersonSegue", sender: c)
  130. case .depart(let d):
  131. if cellViewModel.openFlag {
  132. self.performSegue(withIdentifier: "showDepartPersonSegue", sender: d)
  133. }
  134. case .group(let g):
  135. self.performSegue(withIdentifier: "showPersonGroupSegue", sender: g)
  136. case .identity(let i):
  137. self.performSegue(withIdentifier: "showPersonInfoSegueV2", sender: i)
  138. case .person(let p):
  139. self.performSegue(withIdentifier: "showPersonInfoSegueV2", sender: p)
  140. case .title(_):
  141. break
  142. }
  143. }
  144. override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
  145. if segue.identifier == "showCompanyDepartSegue" {
  146. let destVC = segue.destination as! ContactCompanyDeptController
  147. destVC.superCompany = sender as? Company
  148. }else if segue.identifier == "showDepartPersonSegue" {
  149. let destVC = segue.destination as! ContactDeptPersonController
  150. destVC.superOrgUnit = sender as? OrgUnit
  151. }else if segue.identifier == "showPersonGroupSegue" {
  152. let destVC = segue.destination as! ContactGroupPersonController
  153. destVC.superGroup = sender as? Group
  154. }else if segue.identifier == "showPersonInfoSegueV2" {
  155. let destVC = segue.destination as! ContactPersonInfoV2ViewController
  156. destVC.person = sender as? PersonV2
  157. }
  158. }
  159. func rightItemAction(_ sender:UIBarButtonItem){
  160. //DDLogDebug("rightItemAction haved click")
  161. self.performSegue(withIdentifier: "showContactSearchSegue", sender: nil)
  162. }
  163. func search(by filter: String) {
  164. let sf = SearchFilter(key: filter)
  165. Alamofire.request(self.searchUrl!,method: .put, parameters: sf.toJSON(), encoding: JSONEncoding.default).responseJSON {
  166. response in
  167. switch response.result {
  168. case .success(let val):
  169. DDLogDebug(JSON(val).description)
  170. let value = JSON(val)
  171. if value["type"] == "success" {
  172. if sf.key! == self.searchFilter {
  173. self.searchResult.removeAll()
  174. if let persons = Mapper<PersonV2>().mapArray(JSONString:value["data"].description) {
  175. for person in persons{
  176. let vm = CellViewModel(name: person.name,sourceObject: person)
  177. self.searchResult.append(vm)
  178. }
  179. }
  180. DispatchQueue.main.async {
  181. self.tableView.reloadData()
  182. }
  183. }
  184. }else{
  185. DDLogError("error message =\(value["message"])")
  186. }
  187. case .failure(let err):
  188. DDLogDebug(err as? String ?? "未知错误")
  189. }
  190. }
  191. }
  192. func loadMyData(_ sender:AnyObject?){
  193. let urls = [0:myDepartmentURL,1:myCompanyURL]
  194. var count = 0
  195. //增加常用联系人
  196. self.contacts[2]?.removeAll()
  197. let collectTitle = HeadTitle(name:"常用联系人", icon:"icon_ linkman")
  198. let collectVMT = CellViewModel(name: collectTitle.name, sourceObject: collectTitle)
  199. self.contacts[2]?.append(collectVMT)
  200. let collectPersons = OOContactsInfoDB.shareInstance.queryData((O2AuthSDK.shared.myInfo()?.id)!)
  201. collectPersons.forEach { (p) in
  202. let vm = CellViewModel(name: p.name!, sourceObject: p)
  203. self.contacts[2]?.append(vm)
  204. }
  205. ProgressHUD.show("加载中...")
  206. for (order,url) in urls {
  207. Alamofire.request(url!, method: .get, parameters: nil, encoding:URLEncoding.default, headers: ["X-ORDER":String(order)]).validate().responseJSON {
  208. response in
  209. switch response.result {
  210. case .success(let val):
  211. let objects = JSON(val)["data"]
  212. print(objects.description)
  213. self.contacts[order]?.removeAll()
  214. switch order {
  215. case 1:
  216. let tile = HeadTitle(name: "组织架构", icon: "icon_bumen")
  217. let vmt = CellViewModel(name: tile.name, sourceObject: tile)
  218. self.contacts[order]?.append(vmt)
  219. if let units = Mapper<OrgUnit>().mapArray(JSONString:objects.description) {
  220. for unit in units{
  221. let vm = CellViewModel(name: unit.name,sourceObject: unit)
  222. self.contacts[order]?.append(vm)
  223. }
  224. }
  225. case 0:
  226. let tile = HeadTitle(name: "我的部门", icon: "icon_company")
  227. let vmt = CellViewModel(name: tile.name, sourceObject: tile)
  228. self.contacts[order]?.append(vmt)
  229. if let person = Mapper<PersonV2>().map(JSONString:objects.description) {
  230. if let identities = person.woIdentityList {
  231. for identity in identities {
  232. if let unit = identity.woUnit {
  233. unit.subDirectIdentityCount = 1
  234. let vm = CellViewModel(name: unit.name,sourceObject: unit as AnyObject)
  235. self.contacts[order]?.append(vm)
  236. }
  237. }
  238. }
  239. }
  240. case 2:
  241. break
  242. default:
  243. break
  244. //DDLogDebug(objects.description)
  245. }
  246. case .failure(let err):
  247. DDLogError(err.localizedDescription)
  248. }
  249. count += 1
  250. if count == urls.count {
  251. ProgressHUD.dismiss()
  252. if self.tableView.mj_header.isRefreshing() == true {
  253. self.tableView.mj_header.endRefreshing()
  254. }
  255. }
  256. self.tableView.reloadData()
  257. }
  258. //debugPrint(request)
  259. }
  260. }
  261. }
  262. extension ContactHomeViewController:UISearchControllerDelegate{
  263. func willPresentSearchController(_ searchController: UISearchController) {
  264. NSLog("willPresentSearchController")
  265. searchController.searchBar.searchBarStyle = UISearchBar.Style.default
  266. self.tableView.mj_header.isHidden = true
  267. }
  268. func didPresentSearchController(_ searchController: UISearchController) {
  269. NSLog("didPresentSearchController")
  270. UIView.animate(withDuration: 0.1, animations:{
  271. ()-> Void in
  272. self.tableView.contentInset = UIEdgeInsets(top: 25, left: 0, bottom: 0, right: 0)
  273. })
  274. }
  275. func willDismissSearchController(_ searchController: UISearchController) {
  276. NSLog("willDismissSearchController")
  277. searchController.searchBar.searchBarStyle = UISearchBar.Style.minimal
  278. }
  279. func didDismissSearchController(_ searchController: UISearchController) {
  280. NSLog("didDismissSearchController")
  281. UIView.animate(withDuration: 0.15, animations:{
  282. ()-> Void in
  283. self.tableView.contentInset = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
  284. },completion:{(finished:Bool) -> Void in
  285. self.tableView.mj_header.isHidden = false
  286. })
  287. }
  288. func presentSearchController(_ searchController: UISearchController) {
  289. NSLog("presentSearchController")
  290. }
  291. }
  292. extension ContactHomeViewController:UISearchBarDelegate{
  293. func searchBarCancelButtonClicked(_ searchBar: UISearchBar) {
  294. self.searchFilter = ""
  295. self.searchResult.removeAll()
  296. self.tableView.reloadData()
  297. }
  298. func searchBar(_ searchBar: UISearchBar, selectedScopeButtonIndexDidChange selectedScope: Int) {
  299. NSLog("selectedScopeButtonIndexDidChange")
  300. //self.loadSearchData(searchBar.text, scopeIndex: selectedScope)
  301. }
  302. func searchBarTextDidBeginEditing(_ searchBar: UISearchBar) {
  303. NSLog("searchBarTextDidBeginEditing")
  304. }
  305. // func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
  306. // print("searchBarSearchButtonClicked")
  307. // }
  308. }
  309. extension ContactHomeViewController:UISearchResultsUpdating{
  310. func updateSearchResults(for searchController: UISearchController) {
  311. //let searchBar = searchController.searchBar
  312. //self.loadSearchData(searchBar.text, scopeIndex: searchBar.selectedScopeButtonIndex)
  313. if var filter = searchController.searchBar.text {
  314. filter = filter.trimmingCharacters(in: .whitespaces)
  315. self.searchFilter = filter
  316. if filter != "" {
  317. self.search(by: filter)
  318. }else{
  319. print("no filter to search")
  320. DispatchQueue.main.async {
  321. self.tableView.reloadData()
  322. }
  323. }
  324. }
  325. }
  326. }