O2MainController.swift 15 KB

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