O2MainController.swift 15 KB

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