ContactHomeViewController.swift 19 KB

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