O2MainController.swift 15 KB

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