O2MainController.swift 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375
  1. //
  2. // O2MainController.swift
  3. // O2Platform
  4. //
  5. // Created by FancyLou on 2019/1/25.
  6. // Copyright © 2019 zoneland. All rights reserved.
  7. //
  8. import UIKit
  9. import CocoaLumberjack
  10. import O2OA_Auth_SDK
  11. import Starscream
  12. import AudioToolbox
  13. class O2MainController: UITabBarController, UITabBarControllerDelegate {
  14. static var tabBarVC: O2MainController!
  15. static func genernateVC() -> O2MainController {
  16. // guard let vc = tabBarVC else {
  17. // tabBarVC = O2MainController()
  18. // return tabBarVC
  19. // }
  20. // return vc
  21. return O2MainController()
  22. }
  23. private var currentIndex: Int = 0
  24. // demo服务器弹出公告
  25. private var demoAlertView = O2DemoAlertView()
  26. private let viewModel: OOLoginViewModel = {
  27. return OOLoginViewModel()
  28. }()
  29. //获取消息数量
  30. private lazy var imViewModel: IMViewModel = {
  31. return IMViewModel()
  32. }()
  33. //考勤判断版本
  34. private lazy var attendanceViewModel: OOAttandanceViewModel = {
  35. return OOAttandanceViewModel()
  36. }()
  37. override func viewDidLoad() {
  38. super.viewDidLoad()
  39. if UIDevice.deviceModelReadable() != "Simulator" {
  40. self.checkAppVersion()
  41. }
  42. //
  43. self.tabBar.tintColor = O2ThemeManager.color(for: "Base.base_color")!
  44. self.delegate = self
  45. _initControllers()
  46. selectedIndex = 2
  47. currentIndex = 2
  48. // _loginIM()
  49. if O2IsConnect2Collect == false {
  50. //处理内部直连的时候推送的设备绑定
  51. O2JPushManager.shared.o2JPushBind()
  52. }
  53. //连接websocket
  54. self._startWebsocket()
  55. //读取消息
  56. self.getConversationList()
  57. //检查考勤版本
  58. self.checkAttendanceVersion()
  59. }
  60. deinit {
  61. //关闭websocket
  62. self._stopWebsocket()
  63. }
  64. override func viewDidAppear(_ animated: Bool) {
  65. // 判断是否 第一次安装 是否是连接的demo服务器
  66. if let unit = O2AuthSDK.shared.bindUnit() {
  67. if "demo.o2oa.net" == unit.centerHost || "demo.o2oa.io" == unit.centerHost || "demo.o2server.io" == unit.centerHost || "sample.o2oa.net" == unit.centerHost {
  68. let tag = AppConfigSettings.shared.demoAlertTag
  69. if !tag {
  70. demoAlertView.showFallDown()
  71. AppConfigSettings.shared.demoAlertTag = true
  72. }
  73. }
  74. }
  75. }
  76. //MARK: -- delegate
  77. func tabBarController(_ tabBarController: UITabBarController, didSelect viewController: UIViewController) {
  78. self.currentIndex = tabBarController.selectedIndex
  79. }
  80. private func _initControllers() {
  81. //消息
  82. // let conversationVC = JCConversationListViewController()
  83. let conversationVC = IMConversationListViewController()
  84. conversationVC.title = "消息"
  85. let messages = ZLNavigationController(rootViewController: conversationVC)
  86. messages.tabBarItem = UITabBarItem(title: "消息", image: UIImage(named: "icon_news_nor"), selectedImage: O2ThemeManager.image(for: "Icon.icon_news_pre"))
  87. //通讯录
  88. let addressVC = OOTabBarHelper.getVC(storyboardName: "contacts", vcName: nil)
  89. let address = ZLNavigationController(rootViewController: addressVC)
  90. address.tabBarItem = UITabBarItem(title: "通讯录", image: UIImage(named: "icon_address_g"), selectedImage: O2ThemeManager.image(for: "Icon.icon_address_list_pro"))
  91. // main
  92. let mainVC = mainController()
  93. mainVC.tabBarItem = UITabBarItem(title: nil, image: UIImage(named: "icon_zhuye_nor"), selectedImage: O2ThemeManager.image(for: "Icon.icon_zhuye_pre"))
  94. mainVC.tabBarItem.imageInsets = UIEdgeInsets(top: 6, left: 0, bottom: -6, right: 0)
  95. let blurImage = OOCustomImageManager.default.loadImage(.index_bottom_menu_logo_blur)
  96. let newBlurImage = blurImage?.withRenderingMode(.alwaysOriginal)
  97. mainVC.tabBarItem.image = newBlurImage
  98. let focusImage = OOCustomImageManager.default.loadImage(.index_bottom_menu_logo_focus)
  99. let newFocusImage = focusImage?.withRenderingMode(.alwaysOriginal)
  100. mainVC.tabBarItem.selectedImage = newFocusImage
  101. //应用
  102. let appsVC = OOTabBarHelper.getVC(storyboardName: "apps", vcName: nil)
  103. let apps = ZLNavigationController(rootViewController: appsVC)
  104. apps.tabBarItem = UITabBarItem(title: "应用", image: UIImage(named: "icon_yingyong"), selectedImage: O2ThemeManager.image(for: "Icon.icon_yingyong_pro"))
  105. //设置
  106. let settingsVC = OOTabBarHelper.getVC(storyboardName: "setting", vcName: nil)
  107. let settings = ZLNavigationController(rootViewController: settingsVC)
  108. settings.tabBarItem = UITabBarItem(title: "设置", image: UIImage(named: "setting_normal"), selectedImage: O2ThemeManager.image(for: "Icon.setting_selected"))
  109. self.viewControllers = [messages, address, mainVC, apps, settings]
  110. }
  111. private func mainController() -> UIViewController {
  112. let appid = O2AuthSDK.shared.customStyle()?.indexPortal
  113. let indexType = O2AuthSDK.shared.customStyle()?.indexType ?? "default"
  114. if indexType == "portal" {
  115. let app = DBManager.shared.queryData(appid!)
  116. let destVC = OOTabBarHelper.getVC(storyboardName: "apps", vcName: "OOMainWebVC")
  117. if let mail = destVC as? MailViewController {
  118. mail.app = app
  119. mail.isIndexShow = true
  120. let nav = ZLNavigationController(rootViewController: mail)
  121. return nav
  122. } else {
  123. let nav = ZLNavigationController(rootViewController: destVC)
  124. return nav
  125. }
  126. } else {
  127. let destVC = OOTabBarHelper.getVC(storyboardName: "task", vcName: nil)
  128. let nav = ZLNavigationController(rootViewController: destVC)
  129. return nav
  130. }
  131. }
  132. // MARK: - 考勤判断版本
  133. private func checkAttendanceVersion() {
  134. self.attendanceViewModel.listMyRecords { (result) in
  135. switch result {
  136. case .ok(let data):
  137. let model = data as? OOMyAttandanceRecords
  138. if let s = model?.scheduleInfos, s.count > 0 {
  139. StandDefaultUtil.share.userDefaultCache(value: true as AnyObject, key: O2.O2_Attendance_version_key)
  140. DDLogDebug("考勤打卡新版。。。。。。。。。。。。。。。。。。")
  141. }else {
  142. StandDefaultUtil.share.userDefaultCache(value: false as AnyObject, key: O2.O2_Attendance_version_key)
  143. }
  144. break
  145. case .fail(let err):
  146. DDLogError(err)
  147. StandDefaultUtil.share.userDefaultCache(value: false as AnyObject, key: O2.O2_Attendance_version_key)
  148. break
  149. default:
  150. StandDefaultUtil.share.userDefaultCache(value: false as AnyObject, key: O2.O2_Attendance_version_key)
  151. break
  152. }
  153. }
  154. }
  155. // MARK: - IM message
  156. func getConversationList() {
  157. imViewModel.myConversationList().then { (list) in
  158. var n = 0
  159. if !list.isEmpty {
  160. for item in list {
  161. if let number = item.unreadNumber {
  162. n += number
  163. }
  164. }
  165. }
  166. DispatchQueue.main.async {
  167. DDLogDebug("消息数量: \(n)")
  168. if n > 0 && n < 100 {
  169. self.showRedPoint(number: "\(n)")
  170. } else if n >= 100 {
  171. self.showRedPoint(number: "99..")
  172. }
  173. }
  174. }
  175. }
  176. private func showRedPoint(number: String) {
  177. self.viewControllers?.forEach({ (vc) in
  178. if let zl = vc as? ZLNavigationController, zl.tabBarItem?.title == "消息" {
  179. zl.tabBarItem.badgeValue = number
  180. }
  181. })
  182. }
  183. //消息模块未读消息数量加1
  184. private func addUnreadNumber() {
  185. self.viewControllers?.forEach({ (vc) in
  186. if let zl = vc as? ZLNavigationController, zl.tabBarItem?.title == "消息" {
  187. if let badge = zl.tabBarItem.badgeValue {
  188. if badge != "99.." {
  189. if let n = Int(string: badge) {
  190. let number = n + 1
  191. if number > 0 && number < 100 {
  192. self.showRedPoint(number: "\(number)")
  193. } else if number >= 100 {
  194. self.showRedPoint(number: "99..")
  195. }
  196. }
  197. }
  198. }else {
  199. self.showRedPoint(number: "1")
  200. }
  201. }
  202. })
  203. }
  204. // private func _loginIM() {
  205. // viewModel.registerIM().then { (result) in
  206. // self.viewModel.loginIM().then({ (result) in
  207. // Log.debug(message: "IM登陆完成")
  208. // })
  209. // }.catch { (imError) in
  210. // let error = imError as! OOLoginError
  211. // switch error {
  212. // case .imRegisterFail(let myErr):
  213. // Log.debug(message: myErr.errorDescription!)
  214. // self.viewModel.loginIM().then({ (result) in
  215. // Log.debug(message: "IM登陆完成")
  216. // }).catch({ (loginError) in
  217. // Log.error(message: "im Login Error \(loginError)")
  218. // })
  219. // break
  220. // default:
  221. // break
  222. // }
  223. // }
  224. // }
  225. // MARK: - app update
  226. private func checkAppVersion() {
  227. O2VersionManager.shared.checkAppUpdate { (info, error) in
  228. if let iosInfo = info {
  229. DDLogDebug(iosInfo.toJSONString() ?? "")
  230. let alertController = UIAlertController(title: "版本更新", message: "更新内容:\(iosInfo.content ?? "")", preferredStyle: .alert)
  231. let okAction = UIAlertAction(title: "确定", style: .default, handler: { ok in
  232. O2VersionManager.shared.updateAppVersion(info?.downloadUrl)
  233. })
  234. let cancelAction = UIAlertAction(title: "取消", style: .cancel, handler: { c in
  235. //
  236. })
  237. alertController.addAction(cancelAction)
  238. alertController.addAction(okAction)
  239. UIApplication.shared.keyWindow?.rootViewController?.present(alertController, animated: true, completion: nil)
  240. } else {
  241. DDLogInfo("没有版本更新:\(error ?? "")")
  242. }
  243. }
  244. }
  245. // MARK: - websocket
  246. private var timer: Timer?
  247. private var isWsOpen = false
  248. private func _startWebsocket() {
  249. DDLogDebug("启动websocket连接。。。。。。")
  250. let url = AppDelegate.o2Collect.generateWebsocketURL()
  251. DDLogDebug("这个是wsurl :\(url)")
  252. O2WebsocketManager.instance.startConnect(wsUrl: url, delegate: self)
  253. }
  254. private func _stopWebsocket() {
  255. DDLogDebug("关闭websocket连接。。。。。。")
  256. self.stopTiming()
  257. O2WebsocketManager.instance.closeConnect()
  258. }
  259. private func startTiming() {
  260. DDLogDebug("开启定时器 。。。。。。")
  261. if timer != nil {
  262. timer?.invalidate()
  263. timer = nil
  264. }
  265. timer = Timer.scheduledTimer(timeInterval: 30, target: self, selector: #selector(sendHeartbeatMsg), userInfo: nil, repeats: true)
  266. timer?.fire()
  267. }
  268. private func stopTiming() {
  269. DDLogDebug("关闭定时器 。。。。。。")
  270. if timer != nil {
  271. timer?.invalidate()
  272. timer = nil
  273. }
  274. }
  275. //发送心跳
  276. @objc private func sendHeartbeatMsg() {
  277. if isWsOpen {
  278. O2WebsocketManager.instance.send(msg: o2_im_ws_heartbeat)
  279. } else { //重新启动
  280. _startWebsocket()
  281. }
  282. }
  283. }
  284. extension O2MainController: WebSocketDelegate {
  285. func didReceive(event: WebSocketEvent, client: WebSocket) {
  286. switch event {
  287. case .text(let text):
  288. if text != o2_im_ws_heartbeat { //忽略心跳消息
  289. DDLogDebug("接收的ws消息:\(text)")
  290. //判断type im消息就发送通知
  291. do {
  292. if let dicArr = try JSONSerialization.jsonObject(with: String(text).data(using: .utf8)!, options: .allowFragments) as? [String: AnyObject] {
  293. if let type = dicArr["type"] as? String, type == "im_create" {
  294. if let messageInfo = WsMessage.deserialize(from: text) {
  295. DDLogDebug("接收到im消息 发送通知。。")
  296. NotificationCenter.post(customeNotification: OONotification.websocket, object: messageInfo.body)
  297. }
  298. self.addUnreadNumber()
  299. AudioServicesPlaySystemSound(kSystemSoundID_Vibrate)
  300. }
  301. }
  302. } catch { }
  303. }
  304. break
  305. case .connected(let headers):
  306. DDLogDebug("websocket is connected: \(headers)")
  307. isWsOpen = true
  308. self.startTiming()
  309. break
  310. case .disconnected(let reason, let code):
  311. DDLogDebug("websocket is disconnected: \(reason) with code: \(code)")
  312. isWsOpen = false
  313. break
  314. case .binary(let data):
  315. DDLogDebug("Received binary data: \(data.count)")
  316. break
  317. case .ping(_):
  318. break
  319. case .pong(_):
  320. break
  321. case .viablityChanged(_):
  322. DDLogDebug("websocket viablityChanged")
  323. break
  324. case .reconnectSuggested(_):
  325. DDLogDebug("websocket reconnectSuggested")
  326. break
  327. case .cancelled:
  328. DDLogDebug("websocket is canceled")
  329. isWsOpen = false
  330. break
  331. case .error(let error):
  332. DDLogError("websocket is error, \(String(describing: error?.localizedDescription))")
  333. isWsOpen = false
  334. break
  335. }
  336. }
  337. }